如何在Javascript中压缩多个zip文件?

时间:2015-09-21 13:08:59

标签: javascript zip jszip

问题

我想生成一个ZIP文件,其中包含Javascript中的多个其他ZIP文件。我使用JSZIP,但我无法将ZIP文件添加到一个ZIP文件中。

实施例

我有多个文本文件:

  • 播放器1 - 文件1.txt
  • 播放器1 - 文件2.txt
  • 播放器2 - 文件1.txt
  • 播放器2 - 文件2.txt

我想生成该ZIP文件:

  • example.zip
    • 播放器1.zip
      • 播放器1 - 文件1.txt
      • 播放器1 - 文件2.txt
    • 播放器2.zip
      • 播放器2 - 文件1.txt
      • 播放器2 - 文件2.txt

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

小提琴:https://mikethedj4.github.io/kodeWeave/editor/#ca2d1692722e8f6c321c322cd33ed246

经过几个小时尝试失败后,我终于让它与JSZip一起工作了!

注意:我使用的JSZip v2.6.0目前已过时,不适用于发布时间为3.0的当前版本。

JavaScript

const stuff = {
   data: {
      things: [1,2,3,4]
   }
};
const getThings = ({ data: {things} }) => {
   console.log(things)    
};
getThings(stuff);

HTML

// Set Sample URL
document.getElementById("zipurl").value = "https://mikethedj4.github.io/kodeWeave/editor/zips/font-awesome.zip";

$(".loadzipurl").on("click", function() {
  if ( (!document.getElementById("zipurl").value) ) {
    // Do nothing
    alertify.error("Unable to perform operation as value is blank!");
  } else {
    if ( (document.getElementById("zipurl").value.toLowerCase().substring(0,7) === "http://" ) || (document.getElementById("zipurl").value.toLowerCase().substring(0,8) === "https://") ) {
      JSZipUtils.getBinaryContent(document.getElementById("zipurl").value, function(error, repoFiles) {
        if(error) {
          throw error // or handle err
        }

        var webAppZipBinary = repoFiles;

        // Download as Windows App
        JSZipUtils.getBinaryContent("https://mikethedj4.github.io/kodeWeave/editor/zips/YourLinApp.zip", function(err, data) {
          if(err) {
            throw err // or handle err
          }

          alertify.message("Creating application!");
          var zip = new JSZip();
          zip.load(data);

          // Your Web Application
          zip.folder("HELLOMOMMY/").load(webAppZipBinary);

          // For 32bit Windows Application
          zip.file("package.json", '{\n  "main"  : "index.html",\n  "name"  : "test",\n  "window": {\n      "toolbar" : false,\n      "icon"    : "app/icons/128.png",\n      "width"   : 1000,\n      "height"  : 600,\n      "position": "center"\n  }\n}');
          zip.file("index.html", '<!doctype html>\n<html>\n <head>\n    <title>test</title>\n    <style>\n      iframe {\n        position: absolute;\n        top: 0;\n        left: 0;\n        width: 100%;\n        height: 100%;\n        overflow: visible;\n        border: 0;\n      }\n    </style>\n  </head>\n <body>\n    <iframe src="app/index.html"></iframe>\n  </body>\n</html>');

          // Export your application
          var content = zip.generate({type:"blob"});
          saveAs(content, "test-win.zip");
          return false;
        });
      });
    } else {
      alertify.error("Error! \"http://\" and \"https://\" urls are only supported!");
    }
  }
});
相关问题