The FormData interface is available in all modern browsers as an HTML5 web API. It can be used to store key-value pairs representing form fields and their values.

Once you construct a FormData object, it can be easily sent to the server by using Fetch API, XMLHttpRequest or Axios.

In this article, you'll learn how to upload single or multiple files using FormData in JavaScript.

Uploading Single File

Let us say you have got the following HTML <input> element:

<input type="file" id="avatars">

Now, we want to make sure that when the user selects a file for upload, it is automatically sent to the server for processing.

Here is an example code that you can use for this purpose:

const input = document.querySelector('#avatars');

// Listen for file selection event
input.addEventListener('change', (e) => {
    fileUpload(input.files[0]);
});

// Function that handles file upload using XHR
const fileUpload = (file) => {
    // Create FormData instance
    const fd = new FormData();
    fd.append('avatar', file);

    // Create XHR rquest
    const xhr = new XMLHttpRequest();
    
    // Log HTTP response
    xhr.onload = () => {
        console.log(xhr.response);
    };

    // Send XHR reqeust
    xhr.open('POST', `/upload-avatar`);
    xhr.send(fd);
};

Uploading Multiple Files

The FormData interface can also be used to upload multiple files at once. First of all, add the multiple attribute to the <input> element to allow the user to select more than one files:

<input type="file" id="avatars" multiple>

Next, modify the fileUpload() method to iterate over all selected files and add then to the FormData object:

const input = document.querySelector('#avatars');

// Listen for file selection event
input.addEventListener('change', (e) => {
    fileUpload(input.files);
});

// Function that handles file upload using XHR
const fileUpload = (files) => {
    // Create FormData instance
    const fd = new FormData();

    // Iterate over all selected files
    Array.from(files).forEach(file => {
        fd.append('avatar', file);
    });

    // Create XHR rquest
    const xhr = new XMLHttpRequest();

    // Log HTTP response
    xhr.onload = () => {
        console.log(xhr.response);
    };

    // Send XHR reqeust
    xhr.open('POST', `/upload-avatar`);
    xhr.send(fd);
};

That's it. The server will receive an array of binary files in the avatar request parameter.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .