Skip to content

Instantly share code, notes, and snippets.

@tackme31
Created April 23, 2020 00:21
Show Gist options
  • Select an option

  • Save tackme31/ed7e63aec207359ae568d334a2678bf1 to your computer and use it in GitHub Desktop.

Select an option

Save tackme31/ed7e63aec207359ae568d334a2678bf1 to your computer and use it in GitHub Desktop.
Download a file asynchronously with JavaScript
var url = 'https://sitecorecdn.azureedge.net/-/media/sitecoresite/images/global/logo/sitecore-logo.svg';
download(url);
// => sitecore-logo.svg will be downloaded.
var filename = 'logo.svg';
download(url, filename);
// => 'logo.svg' will be downloaded.
function downloadBlob(blob, filename) {
var anchor = document.createElement('a');
anchor.download = filename;
anchor.href = blob;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
}
function download(url, filename) {
if (!filename) {
filename = url.split('\\').pop().split('/').pop();
}
fetch(url, {
headers: new Headers({
'Origin': location.origin
}),
mode: 'cors'
})
.then(function (response) { return response.blob(); })
.then(function (blob) {
var blobUrl = window.URL.createObjectURL(blob);
downloadBlob(blobUrl, filename);
})
.catch(function (e) { console.error(e); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment