I'm attempting to upload images to an Express server. I'm not exactly sure about how to do this, but heres what I've got from what I've been able to pick up from MDN, express
, react-dropzone
, and multer
Documentation. Multer does not seem to pick up the FormData object from react-dropzone
, when logging out req.file
it returns undefined.
server.js
var storage = multer.diskStorage({
destination: './public/users',
filename: function (req, file, cb) {
switch (file.mimetype) {
case 'image/jpeg':
ext = '.jpeg';
break;
case 'image/png':
ext = '.png';
break;
}
cb(null, file.originalname + ext);
}
});
var upload = multer({storage: storage});
app.use(upload.single('photo'));
app.post('/uploadUserImage', function (req, res) {
console.log(JSON.stringify(req.body.photo)) // form fields
console.log(req.photo) // form files
console.log(req.file) // form files
res.send(req.body.photo);
});
client.js
function uploadImage (image) {
var formData = new FormData();
formData.append('photo', image);
fetch('http://localhost:8080/uploadUserImage/', {
method:'POST',
body: formData
});
}
When I make this request morgan
logs out the following:
{ photo: '[object File]' } <--- from console.log(req.body');
undefined <--- from console.log(req.file);
multer
creates the folder public/uploads
but does not place the image in the location. How can I get the photo because I need to run it through sharp (to compress the filesize and resize the image) and then place it in the uploads
folder?