Dfor
Dfor

Reputation: 348

How to send one or more files to an API using axios in React js?

I am trying to send one or more files (pdf, doc, xls, txt ...) after storing them in the component state, using hooks, to an API. The files are saved together with a file "type", something like the following:

enter image description here

The state object is made up of the file name (key) and inside its key is the file (added using react-dropzone) and the file type (a number)

I have tried to send the files using formData but when trying to do the POST request I get an error 402 {"status": "fail", "data": [{"files": "The files field is required."}] }

This is what I am trying:

const [files, setFiles] = useState({});

const sendFiles = () =>{

    let headers = {
        Authorization: token
    };

    let data = new FormData();
    
    //files is my state
    for(let key in files){
      data.append(key, files[key])
    }

axios
    .post(
        "/some-url/new-files",
        {
          report_id:6, //This is necessary
          
          files: data
        },
        { headers }
    )
    .then(response => {
        let { data } = response.data;
        console.log(data);
      
    })
    .catch(error => {
        console.log(error)
    });
  }



}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 2

Views: 5367

Answers (3)

Dfor
Dfor

Reputation: 348

 let headers = {
        Authorization: "token",
        'Content-Type':'multipart/form-data'
    };

let formData = new FormData();

 for(let key in files){
 
  formData.append('files[][file]', files[key].file, files[key].file.name)
  formData.append('files[][file_type_id]', files[key].fileType)
}

axios
    .post(
        "/api/files",
       formData,
        { headers }
    )
    .then(()=>{console.log('It Works')})

Upvotes: 2

Rıfat Değirmenci
Rıfat Değirmenci

Reputation: 74

let headers = {
        Authorization: token,
       "Content-Type": "application/json",
    };

Upvotes: 0

Rıfat Değirmenci
Rıfat Değirmenci

Reputation: 74

Add to headers Content-Type multipart/form-data,

axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Upvotes: 1

Related Questions