Simple JSZip - Create Zip File From Existing Images

烂漫一生 提交于 2019-12-07 04:26:48

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/24957032/simple-jszip-create-zip-file-from-existing-images

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!