How to upload files with FormData using JavaScript

published: 30 May 2022

2 min read

How to upload files with FormData using JavaScript

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.

How to upload files with FormData using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array, file