Introduction: The company uses JSZip to do some PDF file transfer work, while there is time to get familiar with it.

# JSZiplibrary

  • jszipIs an integrated ZIP file creation, reading, and editing functionalityJavaScriptlibrary

start

  • Routine use of
npm install jszip
Copy the code
  • Use the CDN
    • Cat Cloud CDN can also be introduced for the convenience of first familiarizing and debugging
    • CDN 👉Click on the
< script SRC = "https://cdn.bootcdn.net/ajax/libs/jszip/3.6.0/jszip.min.js" > < / script > < script SRC = "https://cdn.bootcdn.net/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js" > < / script >Copy the code

Learn to use

Start by creating a file upload control

<span> Select file :< span/span><input type="file" id="fileID" /> <hr>
  <button onclick="toZip()" >Zip the selected file and save it</button>
Copy the code

Gets the currently uploaded file object

   var file = document.getElementById("fileID");
   console.log(file.files[0]);
Copy the code

Pass the current file information into the JSzip instance

    var zip = new JSZip();
    /** * zip.file(params1,params2); * Note: *@params1 indicates the current operation file. You can also create *@params2 is the content of the file, or it can be added *@params2 If you add new content, the content will be overwritten in the newly generated compressed file (without affecting the original file) */
    zip.file(file.files[0].name, 'Modified ~~~');
Copy the code

Store the current file and select whether to compress it

    /** * zip. GenerateAsync () * compression: select whether to compress * STORE not to compress (default) * DEFLATE: compress * compressionOptions: configure the compression level from 1 to 9 */
   zip.generateAsync({
      type: "blob".compression: "DEFLATE".compressionOptions: {
         level: 5 
      }
   }).then(function (content) {
      saveAs(content, 'newZip.zip');
   });
Copy the code

Get compressed file binary encoding to file

   var content = "Take the compressed binary data returned by the interface, unpack it and restore it.";
  zip.loadAsync(content).then(function (zip) {
     new_zip.file("getContent.txt").async("string");
  });
Copy the code

Complete compressed sample code

<html>

<head>
  <title>Client compressed file test</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
</head>
<body>
  <span>Select file:</span><input type="file" id="fileID" />
  <hr>
  <button onclick="toZip()">Zip the selected file and save it</button>

  <body>
     <script>
        function toZip() {
           var file = document.getElementById("fileID");
           var zip = new JSZip();
           zip.file(file.files[0].name, file.files[0]);
           zip.generateAsync({
              type: "blob".compression: "DEFLATE".compressionOptions: {
                 level: 5 
              }
           }).then(function (content) {
              saveAs(content, 'newZip.zip');
           });
           if (false) {
              var content = "Here you can take the compressed binary data returned by the interface, restore it and unpack it.";
              zip.loadAsync(content).then(function (zip) {
                 new_zip.file("getContent.txt").async("string"); }); }}</script>
</html>
Copy the code

Unzip the file and display it

  • usingjszip.loadAsyncRead files in the compressed package
   var  base = zip.file(zip.files[key].name).async('string') * You can check the type of text you want in the hierarchy * replace it with: docx JPG PNG PDF etcCopy the code
  • The base content read

  • usingzip.generateAsyncSave the read contents after decompression
   zip.generateAsync({
       type: "blob".compression: "STORE",
    }).then(function (content) {
       saveAs(content, 'unzip.txt');
    });
Copy the code
  • Content can be displayed

  • Addendum: If Chinese characters appear garbled in the text, check the encoding format of the original file

Complete unzip sample code

  <html>

<head>
   <script src="https://cdn.bootcdn.net/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
   <script src="https://cdn.bootcdn.net/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
</head>
<body>
   <span>Select file:</span><input type="file" id="fileID" /><hr>
   <button onclick="readZip()">Unzip the selected file and display it</button><br><br>
   <textarea id="fileTxt">Display text content</textarea>
</body>
<script>
         function readZip() {
            var file = document.getElementById("fileID");
            const zipFile = file.files[0]
            const jszip = new JSZip()
            var dataList=[];
            jszip.loadAsync(zipFile).then((zip) = > { / / read zip
               for (let key in zip.files) { // Loop to determine whether there is a hierarchy
                  if(! zip.files[key].dir) {/** * You can check the type of text you want in the hierarchy * replace it with: docx JPG PNG PDF etc */
                     if (/\.(txt)$/.test(zip.files[key].name)) { 
                        var  base = zip.file(zip.files[key].name).async('string') 
                        // uint8array base64 string
                        // You can choose the type of output you want, such as base64, text string, etc
                        base.then(res= > {
                           dataList.push({
                              fileName: zip.files[key].name,
                              type: 'text'.content: res
                           });
                           // Generate a new file with zip.file() using dataList
                           document.getElementById('fileTxt').innerHTML = res;
                        })
                        zip.generateAsync({
                        type: "blob".compression: "STORE", 
                     }).then(function (content) {
                        saveAs(content, 'unzip.txt'); }); }}}})}</script>

</html>
Copy the code
  • There is also support for various scenarios under the API, specific can see the official introduction
  • More features 👉 click