Skip to content

Instantly share code, notes, and snippets.

@secf4ult
Last active December 8, 2020 08:37
Show Gist options
  • Save secf4ult/e9ea93f91927d00db810fa312c02cbaa to your computer and use it in GitHub Desktop.
Save secf4ult/e9ea93f91927d00db810fa312c02cbaa to your computer and use it in GitHub Desktop.
Download file using JavaScript
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