Created
April 23, 2020 00:21
-
-
Save tackme31/ed7e63aec207359ae568d334a2678bf1 to your computer and use it in GitHub Desktop.
Download a file asynchronously with JavaScript
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
| 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. |
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 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