如何在 Javascript 中生成文本文件并下载 zip 文件?

How to generate text files and download a zip file in Javascript?

我想知道在 Javascript(也许在 JQuery)中最好的方法来在没有服务器编码的情况下做以下事情:

  1. 从对象集生成大约 20 个文本文件。
  2. 将这些文件压缩成 ZIP 文件。
  3. 下载此 ZIP 文件。

1。从对象集生成大约 20 个文本文件

大约有20组对象,每组对象大约有90个对象。这是对象集的示例:

var cardsPlayer1 = {
  name : "Player 1",
  [
    {nbCopies : 3, name : "Noise"},
    {nbCopies : 1, name : "Parasite"},
    {nbCopies : 2, name : "Sure Gamble"},
    ... (around 90 of these objects)
  ]
};

var cardsPlayer2 = 
  name : "Player 2",
  [
    {nbCopies : 1, name : "Gabriel Santiago"},
    {nbCopies : 3, name : "Pipeline"},
    {nbCopies : 2, name : "Aurora"},
    ... (around 90 of these objects)
  ]
};

... (until cardsPlayer20)

生成的文本文件应该是:

player1.txt

3 Noise
1 Parasite
2 Sure Gamble
...

player2.txt

1 Gabriel Santiago
2 Pipeline
2 Aurora
...

...(直到 player20.txt

2。将这些文件压缩成 ZIP 文件

我想将 player1.txt 压缩到 player20.txt 到 ZIP 文件 players.zip。

3。下载此 ZIP 文件

我想下载 ZIP 文件 players.zip。

感谢您的帮助和回答。

只需使用一些 JavaScript zip 库,例如 https://stuk.github.io/jszip/ and a file saver https://github.com/eligrey/FileSaver.js/

jszip 提供了将文件放入 zip 文件所需的所有示例(这涵盖了第 1 点和第 2 点)。对于第 3 点,使用 FileSaver.js 也非常简单。