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.
fetch has no upload progress event, so a progress bar for a large file needs XMLHttpRequest.
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.