Skip to content

Instantly share code, notes, and snippets.

@adinan-cenci
Last active June 20, 2024 20:46
Show Gist options
  • Save adinan-cenci/9fc1d9785700d58f63055bc8d02a54d0 to your computer and use it in GitHub Desktop.
Save adinan-cenci/9fc1d9785700d58f63055bc8d02a54d0 to your computer and use it in GitHub Desktop.
How to follow upload progress with fetch()

How can we follow the upload progress with fetch() ?

Simple: We can't.
Not right now anyway, fetch() does not support that, but good old XMLHttpRequest does though.

The function below behaves much like fetch(), it will return a Promise that will resolve into a Response object.

Just pass a progress function in the options parameter.

async function fetchForm(form, options = {})
{
var method = options.method || form.getAttribute('method') || 'get';
var action = options.url || form.getAttribute('action');
var data = new FormData(form);
var xhr = new XMLHttpRequest();
return new Promise(function(success, failure)
{
xhr.responseType = 'blob';
xhr.onreadystatechange = function()
{
if (xhr.readyState != 4) { // done
return;
}
var response = new Response(xhr.response, {
url : xhr.responseURL,
status : xhr.status,
statusText : xhr.statusText
});
success(response);
}
xhr.addEventListener('error', () =>
{
failure( new TypeError('Failed to fetch') )
});
if (options.progress) {
xhr.addEventListener('progress', options.progress);
}
xhr.open(method, action, true);
xhr.send(data);
});
}
function progress(e)
{
console.log( e.loaded + " loaded of " + e.total );
}
var form = document.getElementById('my-form');
fetchForm(form, { progress });
@MrOxMasTer
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment