Created
February 6, 2014 06:26
-
-
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
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
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); | |
}); |
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 .
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
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!