Created
November 28, 2014 14:55
-
-
Save domharrington/884346cc04c30eeb1237 to your computer and use it in GitHub Desktop.
Download file via ajax. Copied from here http://stackoverflow.com/a/23797348
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
module.exports = downloadAjaxFile | |
function downloadAjaxFile (xhr) { | |
/* jshint maxcomplexity: 7 */ | |
var filename = '' | |
, disposition = xhr.getResponseHeader('Content-Disposition') | |
if (disposition && disposition.indexOf('attachment') !== -1) { | |
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/ | |
, matches = filenameRegex.exec(disposition) | |
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '') | |
} | |
var type = xhr.getResponseHeader('Content-Type') | |
, blob = new Blob([ xhr.responseText ], { type: type }) | |
// 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. | |
if (typeof window.navigator.msSaveBlob !== 'undefined') return window.navigator.msSaveBlob(blob, filename) | |
var URL = window.URL || window.webkitURL | |
, 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment