Skip to content

Instantly share code, notes, and snippets.

@rreimi
Created December 1, 2014 17:29
Show Gist options
  • Save rreimi/2da5ce314b5de3061f44 to your computer and use it in GitHub Desktop.
Save rreimi/2da5ce314b5de3061f44 to your computer and use it in GitHub Desktop.
Ajax blob save as.. file download
var url = 'http://www.pdf995.com/samples/pdf.pdf';
var fileName = 'pdf.pdf';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onprogress = function(pe) {
console.log('progress');
if (pe.lengthComputable) {
console.log((pe.loaded / pe.total) * 100);
}
};
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
//TODO fallback needed for IE8 & IE9
if (navigator.appVersion.toString().indexOf('.NET') > 0) {
//IE 10+
window.navigator.msSaveBlob(blob, fileName);
} else {
//Firefox, Chrome
var a = document.createElement("a");
var blobUrl = window.URL.createObjectURL(new Blob([blob], {type: blob.type}));
document.body.appendChild(a);
a.style = "display: none";
a.href = blobUrl;
a.download = fileName ;
a.click();
}
}
};
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment