Skip to content

Instantly share code, notes, and snippets.

@jgab-net
Last active March 22, 2019 13:17
Show Gist options
  • Save jgab-net/e88b50ecbc4ee56ba621 to your computer and use it in GitHub Desktop.
Save jgab-net/e88b50ecbc4ee56ba621 to your computer and use it in GitHub Desktop.
Download file with xhr2 [blob url & html5 file api]
var url = 'http://backend.siplik.co/public/word-to-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) {
window.open(href=window.URL.createObjectURL(
new Blob([this.response], {type: 'application/pdf'})
));
}
};
xhr.send();
var url = 'http://backend.siplik.co/public/word-to-pdf.pdf';
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
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) {
window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
fs.root.getFile('q.pdf', { create: true }, function (fileEntry) {
fileEntry.createWriter(function (writer) {
writer.onwriteend = function (e) {
window.open(fileEntry.toURL());
console.log('archivo escrito');
}
writer.onwrite = function(e) { console.log(e); };
writer.onerror = function(e) { console.log(e); };
var blob = new Blob([xhr.response], {type: 'application/pdf'});
writer.write(blob);
}, function (e) {
console.log('cw');
console.log(e);
});
}, function (e) {
console.log('fs');
console.log(e);
});
}, function (e) {
console.log('rfs');
console.log(e);
});
}
};
xhr.send();
@wemersonjanuario
Copy link

Very nice! How to save downloaded file in sdcard using cordova?

@palmentierinunzio
Copy link

Hi,
I'm executing both codes (blob and blob_storage) on android, but:
blob shows a blank page
blob_storage print "archivo escrito", but the file is not created.

Can you give me suggestions?

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment