使用JavaScript创建Zip文件

While we're doing amazing things with JavaScript on the server side, it's important not to take our eyes off of some of the great stuff happening on the client side.  One such awesome project I recently discovered was JSZip:  a JavaScript library that allows you to easily generate ZIP files from the front-end.  And why is that useful?  You can allow users to select and download images from a gallery or just about anything else.  Let's have a look at how JSZip allows you to generate structured Zip files from the client side!

尽管我们在服务器端使用JavaScript进行了许多令人惊奇的事情,但重要的是,不要忽视客户端上发生的一些很棒的事情。 我最近发现的一个如此出色的项目是JSZip :一个JavaScript库,可让您轻松地从前端生成ZIP文件。 那为什么有用呢? 您可以允许用户从图库或几乎所有其他内容中选择和下载图像。 让我们看看JSZip如何允许您从客户端生成结构化的Zip文件!

Start by grabbing the JSZip library , which happens to work in all major browsers.  Once the library is available within the page, generating a Zip file is really just a few lines of code:

首先,抓住JSZip库 ,该可在所有主流浏览器中正常工作。 一旦页面中提供了库,生成Zip文件实际上只是几行代码:


var zip = new JSZip();

// Add an top-level, arbitrary text file with contents
zip.file("Hello.txt", "Hello World\n");

// Generate a directory within the Zip file structure
var img = zip.folder("images");

// Add a file to the directory, in this case an image with data URI as contents
img.file("smile.gif", imgData, {base64: true});

// Generate the zip file asynchronously
zip.generateAsync({type:"blob"})
.then(function(content) {
    // Force down of the Zip file
    saveAs(content, "archive.zip");
});


You can add individual files with custom names and contents, as well as arbitrary directories.  Once your contents are added, JSZip can asynchronously generate your Zip file and you can subsequently trigger download.

You can also load and read Zip files:

您可以添加具有自定义名称和内容以及任意目录的单个文件。 添加内容后,JSZip可以异步生成您的Zip文件,随后您可以触发下载。

您还可以加载和读取Zip文件:

var read_zip = new JSZip();
// Load zip content; you'd use fetch to get the content
read_zip.loadAsync(content)
.then(function(zip) {
    // Read from the zip file!
    read_zip.file("hello.txt").async("string"); // a promise of "Hello World\n"
});


I really appreciate JSZip's simplicity.  There are more advanced and complicated libraries available, like zip.js, but JSZip will likely cover most use cases.  One great example of taking advantage of Zip files on the client side is in the Service Worker Cookbook: cache a Zip file locally, extract its contents, and serve within a service worker.  Whatever your use case, know that Zip files can be read and generated without any need for a server!

我非常感谢JSZip的简单性。 有更多高级和复杂的库可供使用,例如zip.js ,但是JSZip可能会涵盖大多数用例。 利用客户端上的Zip文件的一个很好的例子是在Service Worker Cookbook中 :在本地缓存Zip文件,提取其内容,并在Service Worker中提供服务。 无论您使用哪种情况,都知道无需服务器就可以读取和生成Zip文件!

翻译自: https://davidwalsh.name/javascript-zip