I have seen many answers on this and tried almost all of it but none seems to work for me. I can print the form data as ascii chars but I don't see the file stored in the public/uploads folder as expected. I can read and render stored files on react app using API but can't upload it. I get no errors, everything works fine but no file is uploaded in the folder. I'm trying to upload a file using multer and below are the code snippets :
routes/uploads.js
var storage = multer.diskStorage({
dest : function (req, file, cb) {
cb(null, path.join(__dirname, 'public/uploads/'))
}
});
var upload = multer({storage:storage}) ;
router.post('/upload', upload.single('mypic'), function (req, res, next) {
console.log("inside upload files");
console.log(req.body); //prints non-readable characters as I am uploading image as expected
console.log(req.file); //says undefined
return res.status(204).end();
});
API.js (React side):
export const uploadFile = (payload) => //payload is actually formdata
fetch(`${api}/files/upload`,
{
method: 'POST',
//headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: payload
}
)
.then(res => {
console.log(res);
return res.status;
})
.catch(error => {
console.log(error);
return error;
});
Try removing :
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'