简单的JSZip-从现有图像创建Zip文件 [英] Simple JSZip - Create Zip File From Existing Images

查看:361
本文介绍了简单的JSZip-从现有图像创建Zip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找到不涉及Base64或NodeJS的JSZip简单文档.基本上,我有一个目录,其中是test.html和一个名为"images"的文件夹.在该文件夹内是一堆图像.我想从该文件夹中创建一个zip文件.

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.

有人可以为此提供一些非常简单的"hello world"类型代码吗? http://stuk.github.io/jszip/上的文档包括从中添加图像Base64数据或添加您在JavaScript中创建的文本文件.我想从现有文件中创建一个.zip文件.

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.

也许唯一支持通过JSZip将图像添加到.zip文件的方法是通过Base64数据添加图像?我没有在文档中的任何地方看到它,也没有看到image-url-to-base64函数,尽管我确实在StackOverflow的其他地方找到了它.

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.

有什么建议吗?

推荐答案

在浏览器中,您可以使用ajax请求并使用responseType属性获取数组缓冲区(如果需要IE 9支持,则可以使用 jszip-utils ):

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();

此示例的限制,因为它仅处理一个文件并手动创建xhr对象(我没有使用任何库,因为您没有提到任何库),但是应该向您展示如何做

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.

您可以在 JSZip文档中找到更完整的示例:它使用jQuery Promise和jszip-utils下载文件列表,然后触发下载.

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.

如果使用库来处理ajax请求,请确保检查是否可以请求arraybuffer.默认设置是将响应视为文本,这会损坏您的图像.例如,jQuery应该支持很快.

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.

这篇关于简单的JSZip-从现有图像创建Zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆