Last active
December 10, 2023 02:57
-
-
Save ridhotegar/c7618def70e224bc76f6b882ed35e649 to your computer and use it in GitHub Desktop.
Download file with XMLHttpRequest js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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