Course contentsShow
← Web Development
Lesson 2715 of 2,98248. File Uploads and HandlingFree lesson

Single File Upload with Progress

Implement a basic single file upload with progress tracking using XMLHttpRequest or Fetch API with streams.

Single File Upload with Progress

You'll learn how to upload a single file to a server and display real-time progress feedback using the XMLHttpRequest API.

Why Track Upload Progress?

When users upload large files, they need to know the operation hasn't frozen. Progress tracking transforms an uncertain wait into a transparent process — like watching a progress bar while installing software rather than staring at a blank screen.

The Core Approach

We use XMLHttpRequest (not the newer Fetch API yet, as it lacks full upload progress support in most browsers) to send file data. The XHR object fires progress events during the upload, giving us bytes transferred and total bytes.

Here's how it works:

const fileInput = document.getElementById('file-input');
const progressBar = document.getElementById('progress');

fileInput.addEventListener('change', (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const xhr = new XMLHttpRequest();
  const formData = new FormData();
  formData.append('file', file);

  // Track upload progress
  xhr.upload.addEventListener('progress', (e) => {
    if (e.lengthComputable) {
      const percentComplete = (e.loaded / e.total) * 100;
      progressBar.value = percentComplete;
      progressBar.textContent = `${Math.round(percentComplete)}%`;
    }
  });

  xhr.addEventListener('load', () => {
    if (xhr.status === 200) {
      console.log('Upload complete!');
    }
  });

  xhr.open('POST', '/upload');
  xhr.send(formData);
});

The magic happens in xhr.upload.progress: e.loaded tells you bytes sent so far, e.total is the file size. Divide them for a percentage. The lengthComputable check ensures the server sent a proper content length.

Key Takeaway: XMLHttpRequest's upload.progress event provides loaded and total properties to calculate and display upload progress, giving users visual feedback during file transfers.