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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This downloads a terminal and no pdf