How do you send images to node js with Axios?

Here is the way I got this to work properly. I had to make use of an object called FormData. I used the import:

import FormData from 'form-data'

Of course before this import I had to run the npm install for it:

npm install --save form-data

Once I did all that, here is how I used it within my action:

let data = new FormData();
data.append('file', file, file.name);

return (dispatch) => {
axios.post(URL, data, {
  headers: {
    'accept': 'application/json',
    'Accept-Language': 'en-US,en;q=0.8',
    'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
  }
})
  .then((response) => {
    //handle success
  }).catch((error) => {
    //handle error
  });
};}

The important pieces to note here are:

  1. I included some headers as a configuration object after the data object passed into the axios.post call. The content type you're including here is the key. You're submitting a multipart/form-data content type.
  2. Within that Content type header, I also added a boundary, which is derived from the data object you created earlier.
  3. The 'file' used here is just the file object I passed into my action. It's just the name I used for my object, you can use anything you want here.

Hope this helps, this cleared up all of the issues I had with trying to submit an image to a backend (in my case a rest service - through a post call).


Yes you will have to set the content type in your axios request:

axios.put(url, imageFile, {
  headers: {
    'Content-Type': imageFile.type
  }
});

where imageFile is an HTML5 file object which should be an image in your case.