Last active
May 29, 2018 04:44
-
-
Save luanvuhlu/bfc7139157caee5a38e81b2271a5a310 to your computer and use it in GitHub Desktop.
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 ab2str(buf) { | |
return String.fromCharCode.apply(null, new Uint8Array(buf)); | |
} | |
function ajaxDownload(url, params, successCallback, errorCallback){ | |
var xhr = new XMLHttpRequest(); | |
xhr.open('POST', url, true); | |
xhr.responseType = 'arraybuffer'; | |
xhr.onload = function () { | |
if (this.status === 200) { | |
var type = xhr.getResponseHeader('Content-Type'); | |
if(type == null || type.indexOf('text/html') != -1 ){ | |
if(typeof errorCallback === 'function'){ | |
console.debug(xhr.response); | |
errorCallback(ab2str(xhr.response)); | |
} | |
return; | |
}else{ | |
if(typeof successCallback === 'function'){ | |
successCallback(xhr.response); | |
} | |
} | |
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, ''); | |
} | |
filename = decodeURIComponent(filename.replace(/\+/g, " ")); | |
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment