Created
August 6, 2016 00:02
-
-
Save cscuderi/ae05f4a6fa3d3995bba02a83938f8ca1 to your computer and use it in GitHub Desktop.
Download a file using JavaScript
This file contains 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
// Download a PDF | |
var fileName = 'My file'; | |
var fileURL = 'http://localhost/my-file.pdf'; | |
// Non-IE | |
if (!window.ActiveXObject) { | |
var save = document.createElement('a'); | |
save.href = fileURL; | |
save.target = '_blank'; | |
save.download = fileName || 'unknown'; | |
// IE 11 | |
try { | |
var evt = new MouseEvent('click', { | |
'view': window, | |
'bubbles': true, | |
'cancelable': false | |
}); | |
save.dispatchEvent(evt); | |
} catch (e) { | |
window.open(fileURL, fileName); | |
} | |
(window.URL || window.webkitURL).revokeObjectURL(save.href); | |
// IE < 11 | |
} else if ( !! window.ActiveXObject && document.execCommand) { | |
var _window = window.open(fileURL, '_blank'); | |
_window.document.close(); | |
_window.document.execCommand('SaveAs', true, fileName || fileURL) | |
_window.close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment