admin管理员组

文章数量:1318984

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 / 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?

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?

Share Improve this question asked Jul 25, 2014 at 13:35 JakeJake 3,3504 gold badges33 silver badges51 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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 plete 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.

本文标签: javascriptSimple JSZipCreate Zip File From Existing ImagesStack Overflow