Can anyone tell me why my req.file is undefined?
I add the content header type,
I add single.photo but I get no data
frontend:
## data is equal to this:
Object {
"filename": "3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
"type": "image/jpg",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-xxxxx-test/ImagePicker/3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
}
const uploadStory = async data => {
try {
const form = new FormData();
form.append('photo', data);
const options = {
headers: {
'Content-Type':'multipart/form-data',
'Accept':'application/json'
},
method: 'POST',
body: form
};
const res = await fetch('http://xxxxxxx.xx:3000/createstory', options);
const out = await res.json();
return out;
} catch(e) {
console.log(e);
return e;
}
};
export default uploadStory;
backend:
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/')
},
filename: function(req, file, cb) {
console.log(req);
cb(null, `${file.filename}-${Date.now()}`)
}
});
const upload = multer({
storage: storage
}).single('photo');
module.exports = async (req, res, next) => {
upload(req, res, function(err) {
if(err) {
console.log(err)
return;
} else if (err instanceof multer.MulterError) {
console.log(err);
} else {
console.log(req.file);
console.log('hi')
}
});
};
..................................
..................................
..................................
..................................
Make sure your data object looks like this
{
name: "3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
type: "image/jpg",
uri: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-xxxxx-test/ImagePicker/3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
}
In your data Object your key is filename instead of name
Change your upload to this
const upload = multer({
storage: storage,
});
And then,
module.exports = upload.single('photo'), async (req, res) => {
try {
console.log(req.body); // Body Here
console.log(req.file); // File Here
res.status(500).send('Fetch Completed Successfully');
} catch (error) {
console.log(error);
res.status(500).send('Error');
}
}
Related
I am trying to upload an image from my front end to the backend but it it doesn't send the image in the request
It says that the formdata is empty and it says that there's no image found, where is the problem and how can I fix this error?
Here is the code from the Frontend made in react:
const [userInfo, setuserInfo] = useState({
file:[],
filepreview:null,
});
const handleInputChange = (event) => {
setuserInfo({
...userInfo,
file:event.target.files[0],
filepreview:URL.createObjectURL(event.target.files[0]),
});
}
const [isSucces, setSuccess] = useState(null);
const submit = async () =>{
const formdata = new FormData();
formdata.append('avatar', userInfo.file);
console.log(formdata)
Axios.post("http://localhost:4000/imageupload", formdata,{
headers: { "Content-Type": "multipart/form-data" }
})
.then(res => { // then print response status
console.warn(res);
if(res.data.success === 1){
setSuccess("Image upload successfully");
}
})
}
The code of the Backend made in NodeJS:
const storage = multer.diskStorage({
destination: path.join(__dirname, './temp', 'uploads'),
filename: function (req, file, cb) {
// null as first argument means no error
cb(null, Date.now() + '-' + file.originalname )
}
})
app.post('/imageupload', async (req, res) => {
try {
// 'avatar' is the name of our file input field in the HTML form
let upload = multer({ storage: storage}).single('avatar');
upload(req, res, function(err) {
// req.file contains information of uploaded file
// req.body contains information of text fields
if (!req.file) {
return res.send('Please select an image to upload');
}
else if (err instanceof multer.MulterError) {
return res.send(err);
}
else if (err) {
return res.send(err);
}
const classifiedsadd = {
image: req.file.filename
};
res.send("ok")
});
}catch (err) {console.log(err)}
})
Edit:
Multer is essentially a nodejs router,i.e. a function that can be pipelined between your HTTP request and HTTP response.
I think that you should first make multer analyze your HTTP content and to actually populate the req.file before actually evaluate express parsers do their job.
const storage = multer.diskStorage({
destination: path.join(__dirname, './temp', 'uploads'),
filename: function (req, file, cb) {
// null as first argument means no error
cb(null, Date.now() + '-' + file.originalname )
}
})
let upload = multer({ storage: storage});
app.post('/imageupload', upload.single('avatar'), async (req, res) => {
try {
// 'avatar' is the name of our file input field in the HTML form
// req.file contains information of uploaded file
// req.body contains information of text fields
if (!req.file) {
return res.send('Please select an image to upload');
}
else if (err instanceof multer.MulterError) {
return res.send(err);
}
else if (err) {
return res.send(err);
}
const classifiedsadd = {
image: req.file.filename
};
res.send("ok")
}catch (err) {console.log(err)}
})
I am assuming that your upload code is working. Have you tried to read the HTTP request from your browser to see that the image has been correctly attached to the request?
Because probably the issue lies in the fact that you are not actually parsing the image.
const file = new File(userInfo.file, "avatar.png", {
type: 'image/png' // choose the appropriate
});
const formdata = new FormData();
formdata.append('avatar', file);
console.log(formdata)
I am having trouble uploading an image from my react native app. I have a react app that uploads images to the backend from camera as a file.
let pic = await camera.current.takePictureAsync({
quality: 1,
base64: true,
});
setPicture(pic);
Then
onPress={() => {
const formData = new FormData();
formData.append("file", {
name: picture + "",
type: picture.type,
uri:
Platform.OS === "ios"
? picture.uri.replace("file://", "")
: picture.uri,
});
console.log(formData);
httpClient
.post("demo/testsaveimg", formData)
.then((request) => {
if (request.data == "ok") {
console.log(request.data);
}
});
}}
This is my Formdata to service
and then, here is my service
app.post('/testsaveimg', async function (req, res, next) {
let storageUploadFile = multer.diskStorage({
destination: (req, file, next) => {
const folder = './test/'
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder)
}
next(null, folder)
},
filename: (req, file, next) => {
const ext = file.mimetype.slice("/")[1]
next(null, `${file.fieldname}-${Date.now()}.${ext}`)
}
})
let UploadFile = multer({ storage: storageUploadFile }).single("files");
UploadFile(req, res, async function (err) {
console.log(req.file);
if (err instanceof multer.MulterError) {
return res.status(500).json(err);
} else if (err) {
console.log(99);
return res.status(500).json(err);
}
if (req.file != undefined) {
console.log("ok");
res.json("ok")
} else {
console.log("no");
res.json("no")
}
})
})
But there are no pictures in the folder "./test/" and response is "no"
that means "req.file = undefined"
What steps am I doing wrong?
or is there another way to write?
I want to upload the excel file on the MySQL database and then import it back,
I have uses the technologies :
express
multer
mysql2
read-excel-file
sequelize
But when I upload the excel, req.file is showing undefined. in the excel controller folder.
I have checked the multer twice but it seems to be right.
I don't know what is the problem ...
Your answer will help me.
Thanks
Server-side code:
const multer = require("multer");
const excelFilter = (req, file, cb) => {
if (
file.mimetype.includes("excel") ||
file.mimetype.includes("spreadsheetml")
) {
cb(null, true);
} else {
cb("Please upload only excel file.", false);
}
console.log("done");
};
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + "/uploads");
},
filename: (req, file, cb) => {
console.log(file.originalname);
cb(null, `${Date.now()}-bestfile-${file.originalname}`);
},
});
var uploadFile = multer({ storage: storage, fileFilter: excelFilter });
module.exports = uploadFile;
Excel controller
const db = require("../../models");
const Branch = db.bestdata;
const readXlsxFile = require("read-excel-file/node");
const upload = async (req, res) => {
try {
console.log(req);
if (req.file == undefined) {
return res.status(400).send({ msg: "No, Excel File Uploaded" });
}
let path = __basedir + "/uploads/" + req.file.filename;
readXlsxFile(path).then((rows) => {
// skip header
rows.shift();
let branchArray = [];
rows.forEach((row) => {
let branchtoArray = {
id: row[0],
branch_name: row[1],
mgr_id: row[2],
mgr_start_date: row[3],
};
branchArray.push(branchtoArray);
});
Branch.bulkCreate(branchArray)
.then(() => {
res.status(200).send({
message: "Uploaded the file successfully: " + req.file.originalname,
});
})
.catch((error) => {
res.status(500).send({
message: "Fail to import data into database!",
error: error.message,
});
});
});
} catch (error) {
console.log(error);
res.status(500).send({
message: "Could not upload the file: " + req.file.originalname,
});
}
};
const GetImport = (req, res) => {
Branch.findAll()
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving tutorials.",
});
});
};
module.exports = {
upload,
GetImport,
};
Router:
const express = require("express");
const router = express.Router();
const excelController = require("../controller/BestData/excel.controller.js");
const uploadFile = require("../middlewares/upload.js");
let routes = (app) => {
router.post("/upload", uploadFile.single("file"), excelController.upload);
router.get("/import", excelController.GetImport);
app.use("/excel", router);
};
module.exports = routes;
Snapshot of postman test
enter image description here
Excel File uploading
enter image description here
The answer is simple: Destination and path should be the same.:
I am creating a React and Node application, and at the moment I need to upload a PDF file, the code works well, but I was wondering how to use front variables to create the file name by multer.
The code...
Front:
const handleSubmit = async (e) => {
const dado = new FormData()
const year = data.split("/")
const dd = year[0];
const mm = year[1];
const aaaa = year[2];
dado.append('file', file)
dado.append('uni', uni)
dado.append('dd', dd)
dado.append('mm', mm)
dado.append('aaaa', aaaa)
console.log(dado)
axios.post("http://localhost:8080/api/comprebem/file", dado, {
})
.then(res => {
console.log(res.statusText)
})
}
Back:
const storage = multer.diskStorage({
destination:"../login/public/comprebem/ibama/",
filename: function (req, file, cb) {
console.log(file);
cb(null, `unidade${"req['uni']"}_data${file.originalname}` )
}
})
const upload = multer({ storage: storage }).single('file')
app.post('/api/comprebem/file',function(req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
return res.status(500).json(err)
} else if (err) {
return res.status(500).json(err)
}
return res.status(200).send(req.file)
})
});
Don't upload photos to the server, how to solve this problem?
on the page index.ejs a photo gallery should be generated from the added entries. The entry contains a photo. The entry is added, but the photo doesn't load.
project (GitHub)
app/routes.js:
var upload = multer({
storage: storage,
limits: {fileSize: 7},
fileFilter: function (req, file, cd) {
checkFileType(file, cd);
}
}).single('filePhoto');
function checkFiletType(file, cd) {
const fileTypes = /jpeg|jpg/;
const extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = fileTypes.test(file.mimetype);
if (extname && mimetype) {
return cd(null, true);
} else {
cd('Error: only JPEG or JPG!')
}
var Photo = require('../app/models/photo');
module.exports = function (app, passport) {
app.get('/', function (req, res,next) {
Photo.find({}, function (error, photos) {
var photoList = '';
res.render('index.ejs', {photoList: photos});
});
});
}
app.post('/addPhoto', function (req, res, next) {
next();
}, function (req, res) {
var newPhoto = new Photo(req.body);
newPhoto.save().then(function (response) {
console.log('here', response);
res.status(200).json({code: 200, message: 'OK'});
}).catch(function (error) {
console.error('new photo error', error);
});
},function (req, res) {
Photo.find({}, function (error, photos) {
res.send('index.ejs', {
photoList: photos
});
});
});
};
You need to pass your upload var as middleware to your upload route.
Here is a snippet from how I have done it previously:
// Route:
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })
router.post('/upload', upload.single('photo'), ImageController.upload);
// Image Controller:
upload(req, res){
console.log("file", req.file)
}
When I post my image, I make sure I call it photo to match the key word I used in my multer middleware:
So I create my form data like so:
const formData = new FormData()
formData.append('photo', {
uri: data.uri,
type: 'image/jpeg',
});
axios.post(`${SERVER}/images/upload`,
formData: formData,
{ headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => console.log("response", response))
.catch(err => console.log('err', err))