Skip to content
jshacks.dev
APIs

Show upload progress with XMLHttpRequest

Show upload progress with XMLHttpRequest and its upload.onprogress event, because fetch cannot report how many bytes have been sent.

1 min read
Summarize in AI

fetch has no upload progress event, so a progress bar for a large file needs XMLHttpRequest.

upload-progress.jsJavaScript
function upload(file, onProgress) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload');

    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) {
        onProgress(Math.round((event.loaded / event.total) * 100));
      }
    };

    xhr.onload = () => (xhr.status < 300 ? resolve(xhr.responseText) : reject(new Error(`HTTP ${xhr.status}`)));
    xhr.onerror = () => reject(new Error('Network error'));

    const form = new FormData();
    form.append('file', file);
    xhr.send(form);
  });
}

// upload(input.files[0], (percent) => (bar.value = percent));

The events fire on xhr.upload, not on xhr itself, because xhr.onprogress reports the download. loaded and total are in bytes, and lengthComputable is false when the browser cannot tell the size, in which case you should show an indeterminate bar.

The numbers measure what the browser has handed to the network stack, which can be ahead of what the server has received, so 100 percent means the upload has been sent and not that the server has answered. Wait for onload before showing success. Streaming request bodies in fetch may remove this limitation in future, but support is not yet common enough to rely on. See XMLHttpRequestUpload on MDN.

Taggedbrowser
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.