Created
February 17, 2018 03:01
-
-
Save ErvalhouS/6c57041df1545db995057aa0b6f6df5b to your computer and use it in GitHub Desktop.
A JS to download a file given only a link, which can be used to "proxy" requests using javascript response https://stackoverflow.com/a/48837289/3399504
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
//IMPLEMENT THIS PART BELOW | |
// Source: http://pixelscommander.com/en/javascript/javascript-file-download-ignore-content-type/ | |
window.downloadFile = function (sUrl) { | |
//iOS devices do not support downloading. We have to inform user about this. | |
if (/(iP)/g.test(navigator.userAgent)) { | |
//alert('Your device does not support files downloading. Please try again in desktop browser.'); | |
window.open(sUrl, '_blank'); | |
return false; | |
} | |
//If in Chrome or Safari - download via virtual link click | |
if (window.downloadFile.isChrome || window.downloadFile.isSafari) { | |
//Creating new link node. | |
var link = document.createElement('a'); | |
link.href = sUrl; | |
link.setAttribute('target','_blank'); | |
if (link.download !== undefined) { | |
//Set HTML5 download attribute. This will prevent file from opening if supported. | |
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length); | |
link.download = fileName; | |
} | |
//Dispatching click event. | |
if (document.createEvent) { | |
var e = document.createEvent('MouseEvents'); | |
e.initEvent('click', true, true); | |
link.dispatchEvent(e); | |
return true; | |
} | |
} | |
// Force file download (whether supported by server). | |
if (sUrl.indexOf('?') === -1) { | |
sUrl += '?download'; | |
} | |
window.open(sUrl, '_blank'); | |
return true; | |
} | |
window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; | |
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment