Created
December 7, 2016 01:51
-
-
Save kduraiswami/4d2cecc5726e8f5894ef1836ee516129 to your computer and use it in GitHub Desktop.
refactor of stackoverflow answer for this - http://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post
This file contains 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 getFile(link, selected) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('POST', link, true); | |
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); | |
xhr.responseType = 'arraybuffer'; | |
xhr.onload = function () { | |
if (this.status === 200) { | |
formatDownload(this); | |
} | |
}; | |
xhr.send($.param(selected)); | |
} | |
function formatDownload(xhr) { | |
var filename = ""; | |
var disposition = xhr.getResponseHeader('Content-Disposition'); | |
if (disposition && disposition.indexOf('attachment') !== -1) { | |
filename = getFileName(disposition); | |
} | |
var type = xhr.getResponseHeader('Content-Type'); | |
var blob = new Blob([xhr.response], { type: type }); | |
typeof window.navigator.msSaveBlob !== 'undefined' ? window.navigator.msSaveBlob(blob, filename) : downloadBlob(blob, filename); | |
} | |
function getFileName(disposition) { | |
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; | |
var matches = filenameRegex.exec(disposition); | |
if (matches != null && matches[1]) | |
return matches[1].replace(/['"]/g, ''); | |
} | |
function downloadBlob(blob, filename) { | |
var URL = window.URL || window.webkitURL; | |
var downloadUrl = URL.createObjectURL(blob); | |
typeof filename !== 'undefined' ? createDownloadLink(downloadUrl, filename) : window.location = downloadUrl; | |
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); | |
} | |
function createDownloadLink(downloadUrl, filename) { | |
var a = document.createElement("a"); | |
typeof a.download === 'undefined' ? window.location = downloadUrl : clickDownloadLink(a, downloadUrl, filename); | |
} | |
function clickDownloadLink(a, downloadUrl, filename) { | |
a.href = downloadUrl; | |
a.download = filename; | |
document.body.appendChild(a); | |
a.click(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment