JavaScript: how to upload files with the Fetch API

JavaScript: how to upload files with the Fetch API

In JavaScript, the Fetch API allows us to upload files as well.

In JavaScript, the Fetch API allows us to upload files as well.

We can use the FormData object by inserting it as the content of the body property of a POST request:


'use strict';

const uploadFile = async ({ url, fileName, fileData }) => {
    const data = new FormData();
    data.append(fileName, fileData);

    try {
        const req = await fetch(url, { method: 'POST', body: data });
        return await req.json();
    } catch(err) {
        return null;
    }
};

The uploadFile() function accepts as a parameter an object with three properties:

  1. url: the application endpoint that will handle the file upload;
  2. fileName: the file name as it appears as the name attribute of a file input field;
  3. fileData: a reference to the file object obtained by accessing the files array of the input field.

To avoid the callback functions created by then(), the function uses the async/await model to handle Promises created by the fetch() function. It returns a JSON object on successful upload or null on error.

We can use it with an upload form as follows:


const form = document.getElementById('upload');
const fileInput = form.querySelector('#file');

form.addEventListener('submit', evt => {
    evt.preventDefault();
    const params = {
        url: '/api/upload',
        fileName: 'file',
        fileData: fileInput.files[0]
    };
    uploadFile(params).then(results => {
        //...
    });
}, false);

We use the submit event of the form so that it won't be submitted synchronously. Then we use our function specifying the object that contains the parameters for uploading.