How to Implement File Upload Progress in JavaScript Without Misleading Users
JavaScriptUXaccessibilityfrontend developmentfile uploads

How to Implement File Upload Progress in JavaScript Without Misleading Users

SSendFile Online Editorial Team
2026-12-01
7 min read

Build honest JavaScript upload progress with XMLHttpRequest, cancellation, retries, accessibility, and clear handling for unknown transfer sizes.

Accurate upload feedback is more than a moving bar. This guide shows how to report JavaScript file upload progress honestly, support cancellation and retries, handle unknown transfer sizes, and build an accessible experience that remains useful when a connection is slow or a request fails.

Overview

A file upload usually has several distinct stages: selecting files, preparing a request, transferring bytes, processing the server response, and completing any server-side work. A progress indicator should help users understand which stage they are in rather than imply that the entire operation is complete when only the network transfer has finished.

For browser-based uploads, XMLHttpRequest remains the most straightforward native option when you need upload progress events. Its upload object can report how many bytes have been sent and, when the total size is known, calculate a percentage. The Fetch API is useful for requests and cancellation, but upload progress is not exposed through a simple, broadly interchangeable event pattern. If precise client-side upload progress is a core requirement, use XMLHttpRequest or a maintained upload library that provides a suitable progress abstraction. Verify the library's current browser support before adopting it.

A trustworthy implementation follows three rules:

  • Show a percentage only when the browser provides a meaningful total size.
  • Separate “uploading” from “processing” and “complete.”
  • Never leave the user guessing after an error, cancellation, or stalled request.

Progress events describe the transfer from the browser to the server. They do not necessarily describe virus scanning, transcoding, storage, indexing, or other work performed after the request arrives. If the server has additional processing, change the message after the upload reaches 100 percent, such as “Upload received; processing file.”

Checklist by scenario

Single-file upload with XMLHttpRequest

Use a FormData object and attach a listener to xhr.upload. The essential pattern is:

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

xhr.upload.addEventListener('progress', (event) => {
  if (event.lengthComputable) {
    const percent = Math.round((event.loaded / event.total) * 100);
    updateProgress(percent, `${percent}% uploaded`);
  } else {
    updateProgress(null, 'Uploading…');
  }
});

xhr.addEventListener('load', () => {
  if (xhr.status >= 200 && xhr.status < 300) {
    showStatus('Upload received.');
  } else {
    showError('The server rejected the upload.');
  }
});

xhr.addEventListener('error', () => showError('The connection failed.'));
xhr.addEventListener('abort', () => showStatus('Upload canceled.'));
xhr.open('POST', '/api/uploads');
xhr.send(formData);

Do not manually set the Content-Type header when sending FormData. The browser must add the multipart boundary. Setting the header yourself can produce a request the server cannot parse. For related file-type checks, see this MIME types and file extensions reference.

Upload with cancellation

Keep a reference to the active request and expose a clearly labeled Cancel button. With XMLHttpRequest, call xhr.abort(). With Fetch, use an AbortController and pass its signal to fetch:

const controller = new AbortController();

try {
  const response = await fetch('/api/uploads', {
    method: 'POST',
    body: formData,
    signal: controller.signal
  });

  if (!response.ok) throw new Error('Upload failed');
  showStatus('Upload received.');
} catch (error) {
  if (error.name === 'AbortError') {
    showStatus('Upload canceled.');
  } else {
    showError('The upload could not be completed.');
  }
}

// Cancel button handler:
// controller.abort();

This Fetch example demonstrates cancellation and response handling, not a universal upload progress solution. If a fetch-based library reports progress, confirm how it measures bytes and which browsers it supports. Avoid presenting a simulated timer as actual transfer progress.

Multiple files

Decide whether the progress bar represents each file, the whole batch, or both. Per-file progress is clearer when files differ substantially in size. For an overall byte-based percentage, track the total bytes selected and add each file's uploaded bytes to a shared total. Do not average file percentages: a small file at 100 percent and a large file at 10 percent should not appear as 55 percent overall.

Show filenames, sizes, individual states, and a batch summary. A user should be able to identify which file failed and retry that file without necessarily restarting successful uploads. If the backend accepts one file per request, this is usually easier to implement and recover than one large multipart request containing every file.

Unknown transfer length

When event.lengthComputable is false, do not guess the denominator. Use an indeterminate progress bar or a status such as “Uploading file…” and provide a cancel action. If the total size is known from the selected File object but the browser does not expose a usable event total, you may show a carefully labeled estimate only if your implementation has a reliable basis. Otherwise, qualitative status is more honest than a precise-looking percentage.

Large files and resumable workflows

For large files or unreliable connections, consider chunked or resumable uploads. The client can send numbered chunks, retry only the failed chunk, and ask the server which parts have already been received. This requires an explicit protocol, stable upload identifiers, server-side validation, and cleanup for abandoned uploads. A normal XMLHttpRequest progress bar does not by itself make an upload resumable.

What to double-check

  • Progress semantics: Confirm whether the percentage covers bytes sent, bytes acknowledged by the server, or post-upload processing. Label the state accordingly.
  • Server limits: Check request size limits, timeouts, authentication expiry, and accepted multipart field names. A 413, 422, or timeout should produce a useful next step. The file upload errors guide covers common failure categories.
  • Validation: Validate size, type, and content on the server as well as in the browser. Client-side checks improve usability but are not a security boundary. Review the file validation and sanitization guide before processing user uploads.
  • Accessibility: Use a real progress element when a determinate value exists, with an appropriate accessible name. For indeterminate work, communicate status with text. Do not announce every progress event through a live region; frequent announcements can overwhelm screen-reader users. Announce meaningful transitions such as started, canceled, failed, received, and complete.
  • Keyboard and focus behavior: Ensure file selection, cancel, retry, and remove controls work with the keyboard. After an error, place focus on the error or retry control when appropriate, without unexpectedly moving focus during ordinary progress updates.
  • Security and privacy: Use authenticated, appropriately protected upload endpoints; avoid placing sensitive file data in URLs; and define how temporary or failed uploads are removed. If using presigned URLs, make sure the client and storage flow agree on method, headers, expiry, and completion behavior. See the guide to secure presigned file URLs.
  • Testing conditions: Test small and large files, slow connections, offline transitions, server rejection, expired sessions, cancellation near completion, duplicate clicks, multiple files, and a response that succeeds only after lengthy server processing.

Common mistakes

Using a fake percentage

A timer that reaches 100 percent before the request completes creates the most damaging kind of feedback: it tells the user the work is finished when it is not. Use actual progress events or an indeterminate state.

Treating 100 percent as completion

At 100 percent, the browser may have sent the request body, but the server may still be validating or storing it. Wait for a successful response before showing “Complete,” and use a separate processing state where necessary.

Retrying without considering duplicates

A retry can create duplicate files if the first request reached the server but its response was lost. Design a server-side idempotency or deduplication strategy when duplicate creation matters. At minimum, make the UI explain whether retrying starts a new upload or resumes an existing one.

Disabling all controls during upload

Prevent accidental duplicate submissions, but do not remove the user's ability to cancel, inspect status, or remove a queued file. A disabled interface can make a slow upload feel frozen.

Ignoring response details

Check HTTP status codes and parse structured error responses where available. A completed network transfer is not proof that the application accepted the file. Log diagnostic details safely, but show users a concise explanation and a recovery action.

When to revisit

Revisit this implementation before each upload-form release, major UI redesign, backend migration, or change to storage and processing. It is also worth reviewing during seasonal planning cycles if your application experiences periods of larger files, higher traffic, or heavier batch use. Browser behavior, framework upload libraries, and accessibility guidance can change, so confirm the current support assumptions rather than copying an old workaround forward.

Use this final release checklist:

  1. Choose XMLHttpRequest or a suitable upload abstraction when real progress is required.
  2. Define exactly what the percentage measures.
  3. Provide determinate progress only when the total is reliable.
  4. Separate uploading, processing, success, cancellation, and failure states.
  5. Implement cancellation and decide how retries avoid duplicates.
  6. Support keyboard use, readable status messages, and non-visual feedback.
  7. Test slow, interrupted, rejected, oversized, and multi-file uploads.
  8. Document server limits, validation rules, and cleanup for abandoned transfers.

After these checks pass, test the complete flow with the browser tools and network conditions your users actually encounter. Accurate progress is not a decorative percentage; it is a contract between the interface and the transfer system.

Related Topics

#JavaScript#UX#accessibility#frontend development#file uploads
S

SendFile Online Editorial Team

Web Development Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.