0
votes

I cannot seem to upload an image to my uploads folder using express,multer and react-dropzone. My code is as follows:

<Dropzone
    style={{position: "relative"}}
    accept="image/*, video/*"
    onDrop={this.onDrop.bind(this)}
    onDragEnter={this.onDragEnter.bind(this)}
    onDragLeave={this.onDragLeave.bind(this)}
    name='avatar'
  >
    { dropzoneActive && <div style={overlayStyle}>Drop files...</div> }
    <div>

      <h2>Dropped files</h2>
      {

          files.map(f => <div><li>{f.name} - {f.size} bytes</li> 
          <img style={{height:'100px'}}src={f.preview}/></div>)
      }
    </div>
  </Dropzone>

A basic file upload using the dropzone example. Then my submit function is:

createBlog(){

var file = this.state.files[0];
var file_name = file.name;
//api/blog
fetch('http://localhost:8080/saveBlog', {
method: 'POST',
headers: {
  "Accept": 'application/json',
  'Content-Type': 'application/json',
  //"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify({
  file: file,
  file_name: file_name
})
  }).then((response) =>  {
  ...
  }))
  }, function(error) {
   console.log('error: ',error.message)
  })
}

Note that file returns all the properties that image has, E.G. lastModifiedDate, name, preview, size, type, webkitRelativePath.

However, when I pass the data to the server the response I get is :

{ file:
 { preview: 'blob:http://localhost:3000/954e0002-3045-44c4-bcd8-70dc26d0d416' 
},
file_name: 'image.jpg' } 'Body'
undefined 'files'

Where my server code involving the image is :

var multer = require('multer');
var upload = multer({ dest: './uploads/' });
...
...
router.post('/saveBlog', upload.single('avatar'), function(req, res, next) {
    console.log(req.body, 'Body');
    console.log(req.file, 'files');
    res.end();
});

I am hoping someone can help tell me why my images are not going to my uploads folder as I have spent a long time trying to figure out this basic example.

1

1 Answers

2
votes

Your issue is that you're trying using JSON.stringify() for your request payload and Multer expects and only works with formData. You also need to remove the headers you have or use 'content-type': 'multipart/form-data'

You have:

body: JSON.stringify({
  file: file,
  file_name: file_name
}) 

You need to use formData() instead:

createBlog(){

    const file = this.state.files[0];
    const file_name = file.name;
    let data = new FormData();
    data.append('file', file);
    data.append('file_name', file_name);

    fetch('http://localhost:8080/saveBlog', {
       method: 'POST',
       body: data
         }).then((response) =>  {
            ...
         }))
         }, function(error) {
          console.log('error: ',error.message)
    })
}