Monday, 12 June 2017

Sending a file to Multer using Axios

I have a web page that is using Axios. The purpose of this web page is to upload a file to my web server. That server is written with Node and I'm using Express and Multer.

  var fileReader = new FileReader();      
  fileReader.onload = function(e) {
    var data = new FormData();
    data.append('selectedFile', e.target.result);

    axios.post('/upload', data, { headers: { 'Content-Type':null }})
      .then(function (res) {
        console.log('file uploaded');
      })
      .catch(function (err) {
        console.log(err);
      })
    ;
  }

On the server side, I have:

var multer  = require('multer');
var upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('selectedFile'), function(req, res) {
  if (req.file) {
    console.log('file uploaded!');
  } else {
    console.log('no file found');
  }

  res.send({});
});

Whenever this endpoint is reached, it always says "no file found". When I look in Fiddler, I can see the file content is actually being sent. From my understanding, based on this GitHub issue, is that req.file is undefined because how it's sent. However, the content type header is set to null.

How do I send a file to multer using Axios?



via user70192

No comments:

Post a Comment