FormData in JavaScript

May 1, 2020

The JavaScript FormData class is often used to upload files using JavaScript. For example, given a JavaScript file input:

<input type="file" id="my-input">

You can upload the selected file by creating a FormData class and passing it to Axios' post() function.

const input = document.querySelector('#my-input');

const formData = new FormData();
formData.append('myFile', input.files[0]);

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

In short, the FormData class is the easiest way to upload a file from JavaScript without submitting an actual HTML form.


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

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!