如何使用 JavaScript 压缩文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8608724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:42:00  来源:igfitidea点击:

How to Zip files using JavaScript?

javascriptzipzipfile

提问by Isuru

Is there a way to zip files using JavaScript?? For an example, like in Yahoo mail, when you chose to download all the attachments from an email, it gets zipped and downloaded in a single zip file. Is JavaScript capable of doing that? If so, please provide a coding example.

有没有办法使用 JavaScript 压缩文件?例如,就像在 Yahoo 邮件中一样,当您选择从电子邮件中下载所有附件时,它会被压缩并下载到一个 zip 文件中。JavaScript 能做到这一点吗?如果是这样,请提供一个编码示例。

I found this library called jszipto do the task but it has known and unresolved issues.

我发现这个名为jszip 的库可以完成这项任务,但它存在已知和未解决的问题。

How do I solve the problem?

我该如何解决问题?

回答by Yuci

JSZip has been updated over the years. Now you can find it on its GitHub repo

JSZip 多年来一直在更新。现在您可以在其 GitHub 存储库中找到它

It can be used together with FileSaver.js

它可以与FileSaver.js一起使用

You can install them using npm:

您可以使用 npm 安装它们:

npm install jszip --save
npm install file-saver --save

And then import and use them:

然后导入并使用它们:

import JSZip from 'jszip';
import FileSaver from 'file-saver';

let zip = new JSZip();
zip.file("idlist.txt", `PMID:29651880\r\nPMID:29303721`);
zip.generateAsync({type: "blob"}).then(function(content) {
  FileSaver.saveAs(content, "download.zip");
});

Then you will download a zip file called download.zip, once you've extracted it, and you can find inside a file called idlist.txt, which has got two lines:

然后你将下载一个名为 download.zip 的 zip 文件,一旦你解压了它,你可以在一个名为 idlist.txt 的文件中找到它,它有两行:

PMID:29651880
PMID:29303721

And for your reference, I tested with the following browsers, and all passed:

供您参考,我使用以下浏览器进行了测试,均通过:

  • Firefox 59.0.2 (Windows 10)
  • Chrome 65.0.3325.181 (Windows 10)
  • Microsoft Edge 41.16299.371.0 (Windows 10)
  • Internet Explorer 11.0.60 (Windows 10)
  • Opera 52 (Mac OSX 10.13)
  • Safari 11 (Mac OSX 10.13)
  • 火狐 59.0.2 (Windows 10)
  • 铬 65.0.3325.181 (Windows 10)
  • Microsoft Edge 41.16299.371.0 (Windows 10)
  • Internet Explorer 11.0.60 (Windows 10)
  • Opera 52 (Mac OSX 10.13)
  • Safari 11 (Mac OSX 10.13)

回答by A. Tran

I'd recommend going straight to using Node'sbuilt-in library Zlibfor this, which includes images; encode in base 64 using "buffers". Rather than using npmpackages. Reasons being:

为此,我建议直接使用Node 的内置库Zlib,其中包括图像;使用“缓冲区”以 base 64 编码。而不是使用npm包。原因如下:

  • Zlib is a Node native library- has been kept up-to-date for nearly 10 years now - so the proofs there for long-term supports
  • Node allows you work with Buffers- i.e. you can convert your text string/images to the raw binary data and compress it that way with Zlib
  • Easily compress and decompress large files- leverage node streams to compress files in MBs or GBs
  • Zlib 是一个 Node 原生库- 近 10 年来一直保持最新状态 - 所以长期支持的证明
  • Node 允许您使用 Buffers- 即您可以将您的文本字符串/图像转换为原始二进制数据并使用 Zlib 以这种方式进行压缩
  • 轻松压缩和解压缩大文件- 利用节点流以 MB 或 GB 为单位压缩文件

The fact you are using jszip, would allow me to guess that you are using npm as well as node; assumes you have set up your environment correctly, i.e. node installed globally.

您使用 jszip 的事实让我猜测您使用的是 npm 和 node;假设您已正确设置环境,即全局安装节点。

Example: input.txtcompressed to become input.txt.gz

例子:input.txt压缩成input.txt.gz

const zlib = require('zlib');
const fs = require('fs');
const gzip = zlib.createGzip();
const input = fs.createReadStream('input.txt');
const output = fs.createWriteStream('input.txt.gz');

input.pipe(gzip).pipe(output);

Step 1:So you requireeach of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fsmodule, the File Systemmodule.

第 1 步:所以你require每个来自 node-require 的本机模块都是 ES5 的一部分。前面提到的 Zlib 和fs模块,文件系统模块。

const zlib = require('zlib');
const fs = require('fs');

Step 2:The fsmodule, this allows you to create a readstream, are specifically called to read chunks of data. This will return a readstreamobject; readable stream

步骤2:FS模块,这使您可以创建一个readstream,专门打电话来读取数据块。这将返回一个readstream对象;可读流

const input = fs.createReadStream(FILE PATH HERE);

__Note: This readstream object then gets piped again; this chaining of pipes on readsteam objects can occur endlessly, making pipes very flexible.

__注意:这个 readstream 对象然后再次被管道传输;这种 readteam 对象上的管道链接可以无休止地发生,使管道非常灵活。

ReadStream.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)

Step 3:The readstream object, that has been piped and compressed is then converted to writestream object.

第 3 步:经过管道传输和压缩的 readstream 对象然后被转换为 writestream 对象。

const output = fs.createWriteStream('input.txt.gz');

input.pipe(gzip).pipe(output); // returned filename input.txt.gz, within local directory

So this library allows you easily enter a file path and decide where you want your compressed file to be. You can also choose to do the reverse, if need be.

因此,该库允许您轻松输入文件路径并决定压缩文件的位置。如果需要,您也可以选择反向操作。

回答by Sangeetharaj

By using JSZIP we can generate and download zip file in JavaScript. For that you have to follow the steps below

通过使用 JSZIP,我们可以在 JavaScript 中生成和下载 zip 文件。为此,您必须按照以下步骤操作

  1. Download jszip zip file from http://github.com/Stuk/jszip/zipball/master
  2. Extract the zip and find jszip.js file inside dist folder
  3. Import jszip.js file in your html file like below

    <script type="text/javascript" src="jszip.js"></script>
    
  4. Add below function in your code and call it

    onClickDownload: function () {
        var zip = new JSZip();
        for (var i = 0; i < 5; i++) {
            var txt = 'hello';
            zip.file("file" + i + ".txt", txt);
        }
        zip.generateAsync({
            type: "base64"
        }).then(function(content) {
            window.location.href = "data:application/zip;base64," + content;
        });       
    }
    
  5. You can download sample code from my git repository here (GIT link)

  1. http://github.com/Stuk/jszip/zipball/master下载 jszip zip 文件
  2. 解压 zip 并在 dist 文件夹中找到 jszip.js 文件
  3. 在您的 html 文件中导入 jszip.js 文件,如下所示

    <script type="text/javascript" src="jszip.js"></script>
    
  4. 在您的代码中添加以下函数并调用它

    onClickDownload: function () {
        var zip = new JSZip();
        for (var i = 0; i < 5; i++) {
            var txt = 'hello';
            zip.file("file" + i + ".txt", txt);
        }
        zip.generateAsync({
            type: "base64"
        }).then(function(content) {
            window.location.href = "data:application/zip;base64," + content;
        });       
    }
    
  5. 你可以从我的 git 存储库下载示例代码(GIT 链接

回答by Alex Turpin

With the new HTML5 file APIs and the typed arrays, you can pretty much do anything you want in JavaScript. However, the browser support isn't going to be great. I'm guessing that's what you meant by "unresolved issues". I would recommend, for the time being, to do it on the server. For example, in PHP, you could use this extension.

使用新的 HTML5 文件 API 和类型化数组,您几乎可以在 JavaScript 中做任何想做的事情。但是,浏览器支持不会很好。我猜这就是您所说的“未解决的问题”。我建议暂时在服务器上进行。例如,在 PHP 中,您可以使用此扩展。

回答by Jasper

JavaScript is capable of doing this but not in a cross-browser fashion that you can count on.

JavaScript 能够做到这一点,但不是您可以信赖的跨浏览器方式。

This can however be done easily with a server-side language. If you are used to PHP here is the documentation for PHP's ZIP functions: http://php.net/manual/en/book.zip.php

但是,这可以使用服务器端语言轻松完成。如果您习惯 PHP,这里是 PHP 的 ZIP 函数的文档:http: //php.net/manual/en/book.zip.php