如何使用JavaScript压缩文件? [英] How to Zip files using JavaScript?

查看:104
本文介绍了如何使用JavaScript压缩文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我发现这个名为 jszip 的库可以执行此任务,但是它存在已知问题和未解决的问题./p>

我该如何解决问题?

解决方案

JSZip多年来已经更新.现在,您可以在其GitHub存储库上找到它

它可以与 FileSaver.js

一起使用

您可以使用npm安装它们:

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

然后导入并使用它们:

 从'jszip'导入JSZip;从'file-saver'导入FileSaver;让zip = new JSZip();zip.file("idlist.txt",`PMID:29651880 \ r \ nPMID:29303721`);zip.generateAsync({type:"blob"}).then(function(content){FileSaver.saveAs(content,"download.zip");}); 

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

  PMID:29651880PMID:29303721 

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

  • 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)

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.

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

How do I solve the problem?

解决方案

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

It can be used together with FileSaver.js

You can install them using 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:

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)

这篇关于如何使用JavaScript压缩文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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