How to Zip files using JavaScript?

后端 未结 6 1447
不知归路
不知归路 2020-12-09 08:29

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 downloade

相关标签:
6条回答
  • 2020-12-09 08:49

    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.

    0 讨论(0)
  • 2020-12-09 08:52

    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

    0 讨论(0)
  • 2020-12-09 08:54

    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)
    0 讨论(0)
  • 2020-12-09 08:58

    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)

    0 讨论(0)
  • 2020-12-09 09:02

    If you don't care about IE, client-zip is much faster and smaller than JSZip and is meant to solve exactly this problem (yes, this is a shameless but completely relevant plug for my library

    0 讨论(0)
  • 2020-12-09 09:14

    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.

    0 讨论(0)
提交回复
热议问题