Skip to content

Instantly share code, notes, and snippets.

@jasonweng
Created April 21, 2017 08:13
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save jasonweng/393aef0c05c425d8dcfdb2fc1a8188e5 to your computer and use it in GitHub Desktop.
Save jasonweng/393aef0c05c425d8dcfdb2fc1a8188e5 to your computer and use it in GitHub Desktop.
handle file download from AJAX POST
// XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (this.status === 200) {
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([this.response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send($.param(params));
// jQuery ajax
$.ajax({
type: "POST",
url: url,
data: params,
success: function(response, status, xhr) {
// check for a filename
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
});
@edertxodev
Copy link

That help me! Thanks!

@AshwiniGLS28
Copy link

Thank you. It helps me a lot.

@hungtamse
Copy link

Thank you. That help me !

Copy link

ghost commented Nov 26, 2020

hgmhjghkgkj

@GaelCodes
Copy link

Thank you. It is so much helpful.

@rfiedorowicz
Copy link

Thanks for sharing!
Working nice with a lot of files.

Did you try it with zip files generated on Win?
Unfortunately I have problem with charset (I think so), because downloaded zip has few different char that these on the server site

@jasonweng
Copy link
Author

jasonweng commented Mar 23, 2022

@rfiedorowicz
Thanks for the comment.

Did you try it with zip files generated on Win?

I didn't try it but could you provide more details?

@rfiedorowicz
Copy link

rfiedorowicz commented Mar 23, 2022

@jasonweng

Not sure if it because of Windows, but the downloaded file is different (few char, maybe it was because of charset. The file was corrupted).
Good news, I found a solution.
I only used "ajax" solution

I added response type blob, and everything start to working. Maybe it will help somebody :)

$.ajax({
    type: "POST",
    url: url,
    data: params,
    xhr: function(){
      var xhr = new XMLHttpRequest();
      xhr.responseType= 'blob'
      return xhr;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment