javascriptapifileaxios

How to send a list of files in a payload to API by using Axios?


Suppose I have a file selector in front end like <input type="file" />. To send a file to an API with Axios,

we can do the following:

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

However, what if I have a list of files, not just one file. how do I send the list of files to the API? In addition, what if I want to have label on each file with a key in a map, such as

{
  "file_1": file_data_1,
  "file_2": file_data_2,
  ......
}

How can I send the file data alongside with the keys of each file in a payload to an API?


Solution

  • You can create a FormData object, append each file to it with its corresponding label, and then send the FormData object as the payload in the Axios request.

    const files = {
      "file_1": file_data_1,
      "file_2": file_data_2,
    };
    
    const formData = new FormData();
    
    Object.keys(files).forEach((key) => {
      formData.append(key, files[key]);
    });
    
    axios.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })