简体   繁体   中英

How to send a file to axios correctly?

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: 在此处输入图像描述

Console.log my file: 在此处输入图像描述

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: 在此处输入图像描述

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'
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM