Skip to content

Instantly share code, notes, and snippets.

@cscuderi
Created August 6, 2016 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cscuderi/ae05f4a6fa3d3995bba02a83938f8ca1 to your computer and use it in GitHub Desktop.
Save cscuderi/ae05f4a6fa3d3995bba02a83938f8ca1 to your computer and use it in GitHub Desktop.
Download a file using JavaScript
// 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