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'', formData, {
  headers: formData.getHeaders()
});; // 'yinyang.png': an extremely long binary string; // form: { id: '1', string: 'Text we want to add to the submit' }; // ↓
// Accept: 'application/json, text/plain, */*',
// 'Content-Length': '3352',
// 'Content-Type': 'multipart/form-data; boundary=--------------------------a string of numbers that is never the same',
// Host: '',
// '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