Last active
December 8, 2020 08:37
-
-
Save secf4ult/e9ea93f91927d00db810fa312c02cbaa to your computer and use it in GitHub Desktop.
Download file using JavaScript
This file contains 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
const downloader = function (url, filename) { | |
// change these two variables | |
if (!url) throw new Error('url is needed!') | |
filename = filename || 'newfile' | |
fetch(url) | |
.then(res => res.blob()) | |
.then(blob => { | |
const url = URL.createObjectURL(blob) | |
const anchor = document.createElement('a') | |
anchor.href = url | |
anchor.download = filename | |
document.body.appendChild(anchor) | |
anchor.click() | |
anchor.remove() | |
}) | |
} | |
export default downloader |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment