Simple JSZip - Create Zip File From Existing Images
Asked Answered
S

1

7

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?

Soudan answered 25/7, 2014 at 13:35 Comment(0)
B
5

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.

Broadside answered 27/7, 2014 at 21:47 Comment(2)
Looks good, thanks! It's still a crazy way of doing it...I expected more from the library, or at least a native "pass in file, pass in location for .zip" function. I guess using XHR works!Soudan
If it's a remote file, you will have to use ajax requests :) (creating the xhr yourself or using a library). If you don't want to use directly an xhr, you can use a library like stuk.github.io/jszip-utils/documentation/api/… (disclaimer : I worked on this one) or any other ajax lib that can handle binary content (and it's not easy, it requires vbscript on IE9 for example).Broadside

© 2022 - 2024 — McMap. All rights reserved.