【问题标题】:How to generate text files and download a zip file in Javascript?如何在 Javascript 中生成文本文件并下载 zip 文件?
【发布时间】:2015-09-06 06:33:24
【问题描述】:

如果可以的话,我想知道在 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 文件 player.zip。

3。下载此 ZIP 文件

我想下载 ZIP 文件 player.zip。

感谢您的帮助和回答。

【问题讨论】:

    标签: javascript download zip text-files


    【解决方案1】:

    只需使用一些 JavaScript zip 库,例如 https://stuk.github.io/jszip/ 和文件保护程序 https://github.com/eligrey/FileSaver.js/

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

    【讨论】:

    • 看起来很好很简单!谢谢你的回答!
    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    相关资源
    最近更新 更多