Search code examples
javascriptreactjspostaxiosform-data

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>


Solution

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