How to change files using jszip library

I work in a standalone application using HTML5 and jquery for mobile devices. I want to back up files from local storage using jszip. below is a code snippet of what I did ...

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 { } } } 

in the am code above, iterates over the contents of localstorage and saves the ezch file in text format. the problem that is being faced is how to create several text files inside DataFiles.zip , since currently I can only create one text file inside a ZIP folder. I am new to javascript, so naked with any ambiguity in my question. thanks in advance.

+4
source share
3 answers

Just call zip.file() .

Look at the example on the documentation page (my comments):

 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; 

It is important to understand the code that you wrote - to find out what each line does. If you do this, you will realize that you just need to call zip.file() again to add another file.

+10
source

Adding an answer to @Jonathon Reinhart,
You can also specify the file name and path at the same time.

 // create a file and a folder zip.file("nested/hello.txt", "Hello World\n"); // same as zip.folder("nested").file("hello.txt", "Hello World\n"); 
0
source

If you get a list of files (from ui or an array or something else), you can do compression before and after the archive. The code looks something like this:

 function upload(files){ var zip = new JSZip(); let archive = zip.folder("test"); files.map(function(file){ files.file(file.name, file.raw, {base64: true}); }.bind(this)); return archive.generateAsync( { type: "blob", compression: "DEFLATE", compressionOptions: { level: 6 } }).then(function(content){ // send to server or whatever operation }); } 

this worked for me in multiple json files. Perhaps this helps.

0
source

Source: https://habr.com/ru/post/1494647/


All Articles