Search code examples
node.jsexpressmulterform-data

Uploading files in forlder with react/express/multer


I'm trying to upload big files with express and multer.

The call back request send 200 but I don't know really how upload my files in a specific folder. I tried two way without success.

The first one:

app.post('/upload', (req, res, next) => {
  let myFile = req.files;
  let i = 0;

for (i; i < myFile.length; i++) {
    let filemName = MyFile[i].name
    myFile[i].mv(`${__dirname}/uploads/${fileName}`, function(err) {
      if (err) {
        return res.status(500).send(err);
      }
      res.json({file: `uploads/${fileName}`});
    });
  }
})

this code return 500.

The second way (tried only with one file):

app.post ('/uploader', (req, res, next) => {
  var file =  req.files.file;

  // file.mv(`${__dirname}/uploads/${file.name}`), function(err) {
  //   if (err) {
  //     return res.status(500).send(err);
  //   }
  // }
  console.log('file');
  console.log(file[0]);
  fs.rename(req.file[0], '~/dev/file-upload/backend/uploads' +  file[0].name, function (err) {
    if (err) throw err;
    console.log('Move complete');
  })

this code doesn't return any error but doesn't put the file in the folder. And finaly my client side code:

     handleUploadFile(event) {
    event.preventDefault();

    const data = new FormData();

    let c = this.uploadInput.files.length;
    console.log("c = ", c);

    console.log("mydata :", this.uploadInput.files);
    for (var i = 0; i < c; i++){
      data.append('filename', this.uploadInput.files[i].name);
      data.append('file', this.uploadInput.files[i]);
    }

  var options = {
    method: 'post',
    body: data,
  }

    fetch(apiBaseUrl + '/uploader', options).then((response) => {
      console.log('res', response);
    }).catch(function (err) {
      console.error("!!! error :",  err);
    })
  }

  render() {
    return (
      <form onSubmit={this.handleUploadFile}>
        <div>
          <input ref={(ref) => { this.uploadInput = ref; }} type="file"  multiple="multiple" />
        </div>

        <br />
        <div>
          <button>Upload</button>
        </div>    
      </form>
    );
  }

Thanks by advance for your help :)


Solution

  • I fixed my issue.

    body-parser doesn’t support parsing the body of a multipart/form-data request.

    The following link gave me all the answers needed.