Axios Multipart Form Data

Mar 4, 2021

To send multipart form data with Axios, you need to use the FormData class. Browsers have a built-in FormData class, but Node.js doesn't, so you need to use the form-data npm module.

To create the form, you must append the data to the form that will be sent to the server using the append() method. It takes a key and a value as the parameters.

const FormData = require('form-data');
const fs = require('fs');

const formData = new FormData();
formData.append('id', 1);
formData.append('string', 'Text we want to add to the submit');
formData.append('yinyang.png', fs.createReadStream('./yinyang.png'));

const res = await axios.post('https://httpbin.org/post', formData, {
  headers: formData.getHeaders()
});

res.data.files; // 'yinyang.png': an extremely long binary string

res.data.form; // form: { id: '1', string: 'Text we want to add to the submit' }

res.data.headers; // ↓
// Accept: 'application/json, text/plain, */*',
// 'Content-Length': '3352',
// 'Content-Type': 'multipart/form-data; boundary=--------------------------a string of numbers that is never the same',
// Host: 'httpbin.org',
// 'User-Agent': 'axios/0.19.2',
// 'X-Amzn-Trace-Id': 'Root=1-string of numbers and characters that are never the same-ditto'

Note: Axios does not automatically set the multipart form boundary in Node, as a result, you must use getHeaders().


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Axios Tutorials