Skip to content

Instantly share code, notes, and snippets.

@sr9yar
Created January 8, 2021 16:09
Show Gist options
  • Save sr9yar/45036c77d3a692eb33df4e9d99d42b23 to your computer and use it in GitHub Desktop.
Save sr9yar/45036c77d3a692eb33df4e9d99d42b23 to your computer and use it in GitHub Desktop.
Download a file by URL with JS
/**
* Version 1
*/
download(doc?: any): void {
const filename = 'https://via.placeholder.com/350x150';
const link = document.createElement('a');
link.style.display = 'none';
link.href = filename;
link.target = '_blank';
link.setAttribute('download', filename.split('/').pop() );
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
return null;
}
/**
* Version 2
*/
download(): void {
const filename = 'https://via.placeholder.com/350x150';
fetch(filename)
.then(resp => {
if (!resp.ok) {
this.notify.alertDanger(resp.statusText);
}
return resp.blob();
})
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename.split('/').pop();
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
this.notify.alertSuccess('Your download has started.');
})
.catch(e => {
this.notify.alertDanger(e.message);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment