How to Zip files using JavaScript?

可紊 提交于 2019-12-09 05:13:54

问题


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?


回答1:


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)



回答2:


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.




回答3:


I'd recommend going straight to using Node's built-in library Zlib for this, which includes images; encode in base 64 using "buffers". Rather than using npm packages. Reasons being:

  • 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

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.

Example: input.txt compressed to become 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 require each of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fs module, the File System module.

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

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

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.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)

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

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.




回答4:


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

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




回答5:


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

  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)



来源:https://stackoverflow.com/questions/8608724/how-to-zip-files-using-javascript

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