Categories
JavaScript

How to easily upload files using Fetch API?

Every developer comes to a point in a career where he/she needs to upload files to the server. Before, we were using full page reload by providing method and action to our form element. After that AJAX came. We either used jQuery’s $.ajax() API, or Vanilla JS XMLHttpRequest. Today, we have another option and it is fetch().

In order to be able to upload files to a server, first, we need to create form element with input type file.

<form>
    <input type="file" name="upload" id="upload" />
</form>
Upload files form with text on button choose file and disclaimer no files choosen
This is what you should see on your screen once you create a form

After we finish creating form, we can start working on our JavaScript code for uploading files. The first thing we will do is create function that will handle file upload.

JavaScript function to upload files

const uploadFunction = event => {
  const files = event.target.files
  const data = new FormData()
  data.append('file', files[0])

  fetch('/upload-file', {
    method: 'POST',
    body: data
  })
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  .catch(error => {
    console.error(error)
  })
}

Let’s break down our function. Since we are going to use onChange event listener we passed event. When our input recieves files it will trigger an upload. Then we used event.target.files to collect file from our input. After that we created new FormData() to properly encode and send our data to server, in this case to upload files.

Once we succesfully appened our file to FormData() we can begin transmission to our server. We initiate fetch() and provide it with method, in this case POST, and our file. We make POST request to a file on the server called ‘upload-files’.

After our request is successfully finished, we assumed server will send JSON data back, so we can parse it.

Attaching function to event

In order for this function to work in a way we intended it, we need to attach it to event listener.

document.querySelector('#upload').addEventListener('change', event => {
  uploadFunction(event)
})

After we’ve done this our function works. Everytime input#upload changes uploadFunction() will trigger and our files will be uploaded.

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like Array destructuring – everything we need to know.