Reputation: 11
Seems like it's not possible at the moment. Has anyone done it? I just have a few PDF files that I would like to add to a zip folder!
Upvotes: 0
Views: 2386
Reputation: 4069
Sorry for the lack of links in this post : this is my first post on stackoverflow and as the error message says, "[I] need at least 10 reputation to post more than 2 links."
To download a pdf (or any binary file), you can use xhr.responseType = "arraybuffer"
to get the raw content (warning : this won't work in IE 6-9, more on that below). You can't use jQuery to do that (yet, see github.com/jquery/jquery/pull/1525) but a raw xhr query or any ajax library handling binary data will work. For example jszip-utils at github.com/Stuk/jszip-utils (disclaimer : I'm a contributor on this library).
I recently worked (github.com/Stuk/jszip/pull/114) on the JSZip documentation and I added an example of what you're trying to do. The pull request is still pending so here is the temporary url : http://dduponchel.github.io/temp-jszip-documentation/documentation/examples/downloader.html
It should be at http://stuk.github.io/jszip/documentation/examples/downloader.html after the merge.
Here is the code :
This function uses JSZipUtils
and wrap the result into a jQuery.Deferred
but any library that can return an ArrayBuffer or a Uint8Array will work.
/**
* Fetch the content, add it to the JSZip object
* and use a jQuery deferred to hold the result.
* @param {String} url the url of the content to fetch.
* @param {String} filename the filename to use in the JSZip object.
* @param {JSZip} zip the JSZip instance.
* @return {jQuery.Deferred} the deferred containing the data.
*/
function deferredAddZip(url, filename, zip) {
var deferred = $.Deferred();
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
deferred.reject(err);
} else {
zip.file(filename, data, {binary:true});
deferred.resolve(data);
}
});
return deferred;
}
This is the main function, it uses FileSaver.js as a polyfill for saveAs
:
var $form = $("#download_form").on("submit", function () {
var zip = new JSZip();
var deferreds = [];
// find every checked item
$(this).find(":checked").each(function () {
var url = $(this).data("url");
var filename = url.replace(/.*\//g, "");
deferreds.push(deferredAddZip(url, filename, zip));
});
// when everything has been downloaded, we can trigger the dl
$.when.apply($, deferreds).done(function () {
var blob = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(blob, "example.zip");
}).fail(function (err) {
// handle the error here
});
return false;
});
Note on IE 6-9 : jszip and jszip-utils support IE 6-9 but without ArrayBuffer/Uint8Array, you will get poor performances.
EDIT: Link JSZip Utils GitHub: https://github.com/Stuk/jszip-utils
Upvotes: 2