如何使用jszip库压缩文件 [英] How to Zip files using jszip library

查看:569
本文介绍了如何使用jszip库压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在使用HTML5和jquery for mobile处理脱机应用程序。我想使用jszip备份本地存储中的文件。下面是我所做的代码片段...

Am working on an offline application using HTML5 and jquery for mobile. i want to back up files from the local storage using jszip. below is a code snippet of what i have done...

  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 {

                }


            }

        }

循环遍历localstorage内容并以文本格式保存ezch文件。面临的挑战是如何在 DataFiles.zip 中创建多个文本文件,因为目前只能在压缩文件夹中创建一个文本文件。在我的问题中,我对javascript的新手是如此的暧昧。
提前感谢。

in the code above am looping through the localstorage content and saving ezch file in a text format. the challenge that am facing is how to create several text files inside DataFiles.zip as currently am only able to create one text file inside the zipped folder. Am new to javascript so bare with any ambiguity in my question. thanks in advance.

推荐答案

只需继续调用 zip.file()

查看文档页(评论我的):

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});

var content = zip.generate();
location.href="data:application/zip;base64,"+content;

重要的是了解你写的代码 - 学习每条线的作用。如果你这样做,你会发现你只需要再次调用 zip.file()来添加另一个文件。

The important thing is to understand the code you've written - learn what each line does. If you do this, you'd realize that you just need to call zip.file() again to add another file.

这篇关于如何使用jszip库压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆