Skip to content

Instantly share code, notes, and snippets.

@jdelafon
Last active February 11, 2016 09:33
Show Gist options
  • Save jdelafon/6bf34e0e9c1a45e84bd1 to your computer and use it in GitHub Desktop.
Save jdelafon/6bf34e0e9c1a45e84bd1 to your computer and use it in GitHub Desktop.
Trigger a download from Ajax call
/**
* It is actually possible to trigger a download upon return from a GET or POST Ajax request.
* Source: http://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post/23797348#23797348
* Here with jQuery $ajax().
**/
$.ajax({...})
.then(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");
/* Fallback: 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();
}
/* Fallback */
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment