gpt4 book ai didi

javascript - 如何使用 jszip 库压缩文件

转载 作者:搜寻专家 更新时间:2023-11-01 04:57:28 38 4
gpt4 key购买 nike

我正在使用 HTML5 和移动版 jquery 开发离线应用程序。我想使用 jszip 从本地存储备份文件。下面是我所做的代码片段......

  if (localStorageKeys.length > 0) {
for (var i = 0; i < localStorageKeys.length; i++) {
var key = localStorageKeys[i];
if (key.search(_instrumentId) != -1) {
var data = localStorage.getItem(localStorageKeys[i])
var zip = new JSZip();
zip.file(localStorageKeys[i] + ".txt", data);
var datafile = document.getElementById('backupData');
datafile.download = "DataFiles.zip";
datafile.href = window.URL.createObjectURL(zip.generate({ type: "blob" }));
}
else {

}


}

}

在上面的代码中,循环遍历本地存储内容并以文本格式保存 ezch 文件。我面临的挑战是如何在 DataFiles.zip 中创建多个文本文件,因为目前我只能在压缩文件夹中创建一个文本文件。我是 javascript 的新手,所以我的问题没有任何歧义。提前致谢。

最佳答案

继续调用 zip.file()

查看他们的 documentation page 中的示例(评论我的):

var zip = new JSZip();

// Add a text file with the contents "Hello World\n"
zip.file("Hello.txt", "Hello World\n");

// Add a another text file with the contents "Goodbye, cruel world\n"
zip.file("Goodbye.txt", "Goodbye, cruel world\n");

// Add a folder named "images"
var img = zip.folder("images");

// Add a file named "smile.gif" to that folder, from some Base64 data
img.file("smile.gif", imgData, {base64: true});

zip.generateAsync({type:"base64"}).then(function (content) {
location.href="data:application/zip;base64," + content;
});

重要的是理解您编写的代码 - 了解每一行的作用。如果这样做,您会发现只需再次调用 zip.file() 即可添加另一个文件。

关于javascript - 如何使用 jszip 库压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17986432/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com