Created
June 8, 2020 21:23
-
-
Save gorshkov-leonid/d16c3a3bb7cc870c4a2105a6e4a9383b to your computer and use it in GitHub Desktop.
Download file with content disposition attachment
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 downloadFile(url) { | |
var loaded = $.Deferred(); | |
var request = new XMLHttpRequest(); | |
request.open('GET', url); | |
// ! setting the responseType has to be after the `request.open` | |
// `arraybuffer` is necessary for Internet Explorer and Edge becuase | |
// they do not support `blob` as response type | |
request.responseType = "arraybuffer"; | |
request.onload = function() { | |
loaded.resolve(); | |
var contentDisposition = this.getResponseHeader('content-disposition'); | |
var contentType = this.getResponseHeader('content-type'); | |
var filename = contentDisposition.match(/filename="(.+)"/)[1]; | |
var file = new Blob([this.response], { type: contentType }); | |
// For Internet Explorer and Edge | |
if ('msSaveOrOpenBlob' in window.navigator) { | |
window.navigator.msSaveOrOpenBlob(file, filename); | |
} | |
// For Firefox and Chrome | |
else { | |
// Bind blob on disk to ObjectURL | |
var data = URL.createObjectURL(file); | |
var a = document.createElement("a"); | |
a.style = "display: none"; | |
a.href = data; | |
a.download = filename; | |
document.body.appendChild(a); | |
a.click(); | |
// For Firefox | |
setTimeout(function(){ | |
document.body.removeChild(a); | |
// Release resource on disk after triggering the download | |
window.URL.revokeObjectURL(data); | |
}, 100); | |
} | |
}; | |
request.onloadend = function() { loaded.resolve(); }; | |
request.send(); | |
return loaded; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment