Skip to content

Instantly share code, notes, and snippets.

@stripathi669
Created March 31, 2021 11:26
Show Gist options
  • Save stripathi669/0e12749d1241b758e1442bacd80d1821 to your computer and use it in GitHub Desktop.
Save stripathi669/0e12749d1241b758e1442bacd80d1821 to your computer and use it in GitHub Desktop.
jQuery File Download from URL
// if you have url pointing to a file and you want to download a file with a click, normally you can do <a href='url'>.
// But this doesn't work if serving domain and file url domain are not same. This is browser secuirty measure
//For those case, you can use the code below
function downloadFileFromURL(url, filename) {
$.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
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment