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.

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

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.