Skip to content

Instantly share code, notes, and snippets.

@nnarhinen
Created February 6, 2014 06:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nnarhinen/8839233 to your computer and use it in GitHub Desktop.
Save nnarhinen/8839233 to your computer and use it in GitHub Desktop.
Download (multiple) pdf files with ajax and add to a zip file in browser
var JSZip = require('jszip'),
Q = require('q');
var downloadFile = function(url) {
var defer = Q.defer();
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status < 400) {
defer.resolve(xhr.response);
} else {
defer.reject(new Error("Failed to load file from server"));
}
}
};
xhr.send();
return defer.promise;
};
var files = [{filename: 'foo.pdf', url: '/files/foo.pdf'}, {filename: 'bar.pdf', url: '/files/bar.pdf'}],
zip = new JSZip();
files.reduce(function(p, o) {
return p.then(function() {
return downloadFile(o.url).then(function(arrayBuffer) {
zip.file(o.filename, arrayBuffer);
});
})
}, Q()).then(function() {
var link = document.getElementById('download-link'),
blob = zip.generate({type:"blob"}),
link.download = 'myzip.zip';
link.href = window.URL.createObjectURL(blob);
});
@frankydp
Copy link

Am i right in thinking that this streams the xhr arraybuffer into the zip "blob"? Have you thought of anyway to download in parallel, I would think you would run into browser caps without fileAPI.

Great gist!

@irfancheema
Copy link

Does this work on IE9+?. I tried to download multiple pdf files from web with JSZip using ajax call but it does'nt work on IE11. Same code runs on Chrome and Firefox without any issue .

@jp-bitcube
Copy link

This downloads a terminal and no pdf

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