Cordova --- JSZip で複数ファイルを圧縮して BLOB Type で zip 保存する


Platform

  • Cordova

Library

Usage

compress.js
let jsZip = new JSZip();
var destFolderPath = cordova.file.externalDataDirectory; // *1
var zipFileName = 'MyZip.zip';
jsZip.file( 'filePath_1' );
jsZip.file( 'filePath_2' );
// And so on...
jsZip.generateAsync(
    {type:"blob",
     compression: "DEFLATE",
     compressionOptions: {level: 1} // level: 1->fastest, 9->best compression ratio
    }).then(function (blob) {
         window.resolveLocalFileSystemURL(destFolderPath, (fileEntry)=>{ // *1
             fileEntry.getFile( zipFileName, {create: true}, (entry)=>{ // *1
                 entry.createWriter( (fileWriter)=>{ // *2 create a file writer
                     fileWriter.write(blob); // *2 save zip file
                     resolve(destFolderPath + zipFileName); // Return full file path
                 }, (error)=>{
                     reject(error);
                 });
             });
         });
    }
);

Reference

*1 https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/
*2 https://cordova.apache.org/docs/en/2.7.0/cordova/file/filewriter/filewriter.html
JSZip:https://stuk.github.io/jszip/documentation/examples.html