Skip to content

How to upload a file using Fetch

How to upload files to the server using the Fetch API, explained in a simple way

There’s a task that should be simple, but sometimes it leads to hours of research on the Web: uploading files to the server.

In this tutorial I explain you how to do so using fetch.

Given a form with a file input field:

<input type="file" id="fileUpload" />

We attach a change event handler on it:

document.querySelector('#fileUpload').addEventListener('change', event => {
  handleImageUpload(event)
})

and we manage the bulk of our logic in the handleImageUpload() function:

const handleImageUpload = event => {
  const files = event.target.files
  const formData = new FormData()
  formData.append('myFile', files[0])

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

In this example we POST to the /saveImage endpoint.

We initialize a new FormData object and we assign it to the formData variable, and we append there the uploaded file. If we have more than one file input element, we’d have more than one append() call.

The data variable inside the second then() will contain the JSON parsed return data. I’m assuming your server will give you JSON as a response.

See how to handle images uploaded server-side


→ Get my JavaScript Beginner's Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list