Simple JSZip - Create Zip File From Existing Images

Jake picture Jake · Jul 25, 2014 · Viewed 8k times · Source

I'm having a hard time finding easy documentation for JSZip that doesn't involve Base64 or NodeJS. Basically, I have a directory, in which is test.html and a folder called "images". Inside that folder is a bunch of images. I would like to make a zip file out of that folder.

Can anyone help me with some very simple "hello world" type code for this? The documentation on http://stuk.github.io/jszip/ includes things like adding an image from Base64 data or adding a text file that you create in JavaScript. I want to create a .zip file from existing files.

Perhaps the only support for adding images to .zip files with JSZip involves adding them via Base64 data? I don't see that anywhere in the documentation, nor an image-url-to-base64 function, though I did find one elsewhere on StackOverflow.

Any advice?

Answer

David Duponchel picture David Duponchel · Jul 27, 2014

In a browser you can use an ajax request and use the responseType attribute to get an arraybuffer (if you need IE 9 support, you can use jszip-utils for example) :

var xhr = new XMLHttpRequest();
xhr.open('GET', "images/img1.png", true);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function(evt) {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            var zip = new JSZip();
            zip.file("images/img1.png", xhr.response);
        }
    }
};
xhr.send();

This example is limited because it handles only one file and manually creates the xhr object (I didn't use any library because you didn't mention any) but should show you how to do it.

You can find a more complete example in the JSZip documentation : it uses jQuery promises and jszip-utils to download a list of files and trigger a download after that.

If you use a library to handle the ajax request, be sure to check if you can ask for an arraybuffer. The default is to treat the response as text and that will corrupt your images. jQuery for example should support it soon.