Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Building AJAX User Interfaces

File Uploads and Progress Bars

Upload files with FormData and fetch, validate them first, show real upload progress with XMLHttpRequest, queue many files, split big files into chunks and cancel an upload.

Sending a name and an email is easy; sending a 40 MB video is a different job. Files are big, so uploads take time, and time brings new problems: the user wants to see progress, wants to cancel, may drop ten photos at once, and may lose their connection halfway. A good upload interface handles all of that, and it checks the files before wasting the user's bandwidth.

This lesson builds those pieces one at a time: picking and validating files, sending them with FormData, showing real progress, uploading many files through a queue, splitting very large files into chunks and cancelling. The earlier forms lesson showed the basics of a file field; here we go much deeper.

About the examples. The editors on this site cannot send real uploads, because they run in a sandbox without a server to receive files. The runnable examples therefore use real File and Blob objects with a simulated upload that behaves like the real thing (it fires progress events and can fail or be cancelled). The code labelled "Read-only" is the real network version, ready to point at your own server.

Picking files

A file input gives you File objects. A File is a Blob with a name, a lastModified time and a type:

HTML
<!-- Read-only -->
<input type="file" id="picker" multiple accept="image/png, image/jpeg">
JavaScript
// Read-only
picker.addEventListener("change", () => {
  for (const file of picker.files) {
    console.log(file.name, file.type, file.size);   // size is in bytes
  }
});

multiple lets the user choose several files, and accept filters the file picker. But accept is only a hint: users can switch the dialog to "All files", and dropped files ignore it entirely. Always validate in JavaScript, and again on the server.

Validating before you upload

Check the cheap things first (count, size, declared type), and for important cases look at the file's first bytes. The type of a file comes from its extension, so a renamed virus.exe can claim to be image/png. Real image formats start with fixed "magic numbers" you can read with file.slice(0, 4):

JS Validate size, type and file signature

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The renamed program is caught because its first bytes are not a PNG signature. Client-side checks improve the experience and save bandwidth, but they are not security: anyone can bypass your JavaScript, so the server must repeat every check.

Sending files with FormData

FormData builds a multipart/form-data body, the format browsers use for file forms. Append each file under the field name your server expects, and hand the object to fetch():

JavaScript
// Read-only: the real network version
async function uploadFile(file, signal) {
  const body = new FormData();
  body.append("file", file);                // the File itself, not its contents as text
  body.append("albumId", "42");             // other fields can travel with it

  const response = await fetch("/api/uploads", { method: "POST", body, signal });
  if (!response.ok) throw new Error("Upload failed: " + response.status);
  return response.json();                   // for example { id: 7, url: "/files/7.png" }
}

Two rules matter:

  1. Do not set a Content-Type header yourself. The browser must write multipart/form-data; boundary=..., including a random boundary string only it knows. If you override the header, the boundary is lost and the server cannot parse the body.
  2. Files are streamed from disk, not loaded into memory, so large files are fine.

For several files, either append them all to one FormData (body.append("files", file) repeated; one request, all or nothing) or send one request per file. One request per file is usually better: a single failure does not lose the others, and you get per-file progress.

Real upload progress with XMLHttpRequest

fetch() has no standard way to report how much of the request body has been sent. XMLHttpRequest does, through xhr.upload events (the XHR lesson covers its API). Wrapped in a promise it looks like this:

JavaScript
// Read-only: the real network version
function uploadWithProgress(file, { onProgress, signal }) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    const body = new FormData();
    body.append("file", file);

    xhr.open("POST", "/api/uploads");

    xhr.upload.addEventListener("progress", (event) => {
      if (event.lengthComputable) onProgress(event.loaded / event.total);
    });
    xhr.addEventListener("load", () => {
      if (xhr.status >= 200 && xhr.status < 300) resolve(JSON.parse(xhr.responseText));
      else reject(new Error("Server said " + xhr.status));
    });
    xhr.addEventListener("error", () => reject(new Error("Network error")));
    xhr.addEventListener("abort", () => reject(new DOMException("Upload cancelled", "AbortError")));

    signal?.addEventListener("abort", () => xhr.abort());
    xhr.send(body);
  });
}

Progress events report loaded and total bytes sent, not bytes processed by the server: the bar can reach 100 % while the server is still saving the file. Show "Processing..." after it fills, and wait for the load event before saying "Done".

The next example gives you the full interface with a simulated upload that has the same event names, so you can see the progress bar, the cancel button and the error handling without a server. In your own project, swap fakeUpload for uploadWithProgress:

Progress bar, cancel and error handling

Notice how AbortController and the promise shape make cancellation, success and failure three clean outcomes, the same pattern as in Aborting and Timeouts.

Uploading many files with a queue

If a user drops 50 photos, starting 50 uploads at once saturates the connection and every file crawls. Browsers also limit parallel connections per host. A queue with a concurrency limit starts a few uploads at a time and begins the next one as soon as a slot frees up. Failed files are reported without stopping the rest:

JS An upload queue with two workers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two "workers" pull from the same list, so there are never more than two uploads in flight, yet all five files finish. Each result keeps the file's position, which makes it easy to draw a per-file status list.

Drag and drop upload

A drop zone uses the events you met in The Drag and Drop API: cancel dragover, then read event.dataTransfer.files in drop. Feed those files into the same validation and queue as the file input, so both paths behave identically:

JavaScript
// Read-only
zone.addEventListener("dragover", (event) => event.preventDefault());
zone.addEventListener("drop", (event) => {
  event.preventDefault();
  handleFiles([...event.dataTransfer.files]);   // same function the <input> change event calls
});
picker.addEventListener("change", () => handleFiles([...picker.files]));

Keep the <input type="file"> visible or reachable by keyboard: a drop zone alone excludes people who cannot drag.

Previewing an image before it uploads

URL.createObjectURL(file) creates a short-lived URL pointing at the file in memory, so you can show a thumbnail instantly with no network at all. Release it when you no longer need it:

JavaScript
// Read-only
const img = document.createElement("img");
img.src = URL.createObjectURL(file);
img.onload = () => URL.revokeObjectURL(img.src);   // free the memory
preview.append(img);

Chunked uploads for very large files

Sending a 2 GB file in one request is fragile: one dropped packet and you start over, and servers and proxies often cap request size. A chunked upload slices the file with file.slice(start, end) and sends the pieces in order, so a failure only repeats one chunk, and an interrupted upload can resume from the first missing chunk. Production systems use protocols such as tus, or direct-to-storage services with pre-signed URLs, where your server hands the browser a temporary, single-purpose address so the file goes straight to cloud storage.

The core of chunking is easy to see with real Blob objects. This example splits a file, uploads each chunk through a simulated server that fails the first attempt of one chunk, and retries it:

JS Chunked upload with a retry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last chunk is smaller than the rest (3500 is not a multiple of 1024), and the failed chunk is simply sent again without touching the others. A real implementation also tells the server the total number of chunks, so it can assemble the file and ask "which chunks do you already have?" when the user returns.

What the server must still do

Everything in this lesson improves the user's experience. The server is where uploads are made safe:

  • Enforce its own size limit and file count, and reject anything over it.
  • Check the real contents, not the name or Content-Type the browser claimed.
  • Generate a new file name yourself; never trust file.name, which can contain path tricks like ../.
  • Store uploads outside the web root, or on object storage, so an uploaded script is never executed.
  • Scan or re-encode risky formats, and require the user to be authenticated.

See Security for AJAX for the wider picture, and OAuth, Tokens and Sessions for API Calls for how to send credentials with upload requests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should you not set the Content-Type header yourself when sending FormData with fetch()?

    multipart/form-data needs a boundary string. The browser generates it and writes the full header; overriding the header drops the boundary and the body cannot be parsed.
  2. 2. Which API reports how many bytes of a request body have been sent?

    fetch() has no standard upload progress. XMLHttpRequest exposes it through xhr.upload.addEventListener('progress', ...).
  3. 3. Why is the accept attribute on a file input not enough validation?

    accept filters the dialog but does not stop other files from arriving. Validate with JavaScript, and again on the server.
  4. 4. What is the benefit of a queue with a concurrency limit when uploading 50 files?

    Running a few uploads at a time keeps each fast, and results are tracked individually so one failure does not stop the rest.
  5. 5. In a chunked upload, what does file.slice(start, end) return?

    slice() creates a Blob for the requested byte range, so each chunk can be uploaded and retried separately.

Summary

  • A file input gives you File objects (name, size, type). accept is only a hint, so validate count, size, type and, where it matters, the first bytes.
  • Send files with FormData and fetch(), and never set Content-Type yourself.
  • For real upload progress, use XMLHttpRequest with xhr.upload events; cancel with AbortController or xhr.abort().
  • Upload many files through a queue with limited concurrency, one request per file.
  • Use drag and drop and image previews (URL.createObjectURL) as conveniences on top of the same logic.
  • For very large files, slice into chunks with retries, or upload directly to storage with pre-signed URLs.
  • Client checks are only for the user's benefit; the server must enforce size, type, naming and storage rules.

Next, make search boxes feel instant: Live Search and Pagination.