Uploading images with fetch to Express using Multer

guyforlowbro picture guyforlowbro · May 27, 2016 · Viewed 10k times · Source

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?

Answer

gnerkus picture gnerkus · May 27, 2016

The error occurs because you specified the 'Content-type' explicitly. To do this properly, you'd also need to specify the boundary. You can find a detailed explanation of multipart/form-data here: How does HTTP file upload work?

To solve the issue with the file upload, you should remove the 'Content-Type' specification from the fetch request. You can also refactor the uploadImage method to upload the form without parsing the inputs:

function uploadImage () {
  // This assumes the form's name is `myForm`
  var form = document.getElementById("myForm");
  var formData = new FormData(form);
  fetch('http://localhost:8000/uploadUserImage', {
    method: 'POST',
    body: formData
  });
}