0

How to send a file to axios correctly?

File:

const onHandleFileRender = e => {
if(e.target.files[0] !== null) {
  const file = e.target.files[0];
  setFileData(file);
}

};

Request:

newFile = data => {
// data - my img
return axios.post(`${this._url}/api/v1/files`, data, {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
});

Error: enter image description here

Console.log my file: enter image description here

UPD: My request:

  newFile = data => {
    const formData = new FormData();
    formData.append("image", data);

    return axios.post(`${this._url}/api/v1/files`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  };

Error: enter image description here

  • 1
    https://stackoverflow.com/questions/43013858/how-to-post-a-file-from-a-form-with-axios – reddiky May 20 '20 at 13:10
  • Does this answer your question? [How to post a file from a form with Axios](https://stackoverflow.com/questions/43013858/how-to-post-a-file-from-a-form-with-axios) – reddiky Jun 02 '20 at 14:22

1 Answers1

0

You seem to be missing to use FormData

This should work

newFile = data => {
let formData = new FormData();
formData.append("image", data); //<--------- change the name(image) to anything that your backend requires
return axios.post(`${this._url}/api/v1/files`, formData, {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
});
gdh
  • 13,114
  • 2
  • 16
  • 28