How to implement file upload with progress tracking in JavaScript
· Category: JavaScript & Web
Short answer
Use XMLHttpRequest with the progress event for granular upload progress, or the Fetch API with ReadableStream for modern streaming uploads.
Details
With XMLHttpRequest, attach an upload.onprogress listener to compute percentage completion:
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => {
const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0;
updateProgressBar(percent);
};
xhr.open('POST', '/upload');
xhr.send(formData);
Wrap this logic in async/await helpers if you want promise-based control flow. Always handle errors with try/catch around network calls, checking for timeouts, aborts, and HTTP error codes. For drag-and-drop UIs, use the drop event on a container and validate file types and sizes on the client before uploading. Chunk large files to allow resumable uploads and reduce memory pressure.
Tips
- Validate file types on the server as well; client checks are bypassable.
- Use
FormDatato bundle multiple files and metadata in one request. - Show an indeterminate spinner when total size is unknown to maintain perceived performance.