Skip to content

Instantly share code, notes, and snippets.

@ridhotegar
Last active December 10, 2023 02:57
Show Gist options
  • Save ridhotegar/c7618def70e224bc76f6b882ed35e649 to your computer and use it in GitHub Desktop.
Save ridhotegar/c7618def70e224bc76f6b882ed35e649 to your computer and use it in GitHub Desktop.
Download file with XMLHttpRequest js
function save(blob) {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'zip_10MB.zip'; //filename
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
alert('your file has downloaded!');
}
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://file-examples-com.github.io/uploads/2017/02/zip_10MB.zip", true);
xhr.responseType = 'blob';
xhr.onprogress = e => console.log(`${parseInt((e.loaded/e.total)*100)}%`)
xhr.onload = e => save(xhr.response)
xhr.send()
/*
Reference
https://stackoverflow.com/a/52738942
https://stackoverflow.com/a/9834261
https://stackoverflow.com/a/64123890
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment