安装
npm install jszip --save
npm install file-saver
引入
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
使用
const zip = new JSZip()
// 方法1直接创建文件 zip.file('hello.txt', blob) blob为文件流
zip.file('hello.txt', 'hello world\n')
// 方法2先创建文件夹然后再在文件夹中添加文件
zip.folder('nested').file('hello.txt', 'hello world\n')
const folder = zip.folder('folder')
folder.file('hello.txt', 'hello world\n')
// 方法3添加文件时可以直接添加文件流
const blob = new Blob(['hello world\n'], {type: 'text/plain;charset=utf-8'})
zip.file('hello.txt', blob)
/**
* @param {String} type 文件格式uint8array\string\blob\array\arraybuffer\base64\text\nodebuffer\binarystring.
* @param {String} compression 是否压缩 DEFLATE压缩,STORE无压缩,默认值STORE
* @param {Object} compressionOptions 压缩等级设置来控制压缩速度和效果,默认null compressionOptions: {level: 9}
* @param {String} comment 指定zip文件的注释
* @param {String} mimeType 指定zip文件的MIME类型,可以是application/zip或者其他类型(application/ods),默认application/zip,用于创建zip文件时设置文件的Content-Type,以便在下载或传输zip文件时正确解析文件类型
* @param {String} platform 指定zip文件的平台标识,可以设置为UNIX,DOS,OS/2,默认为DOS
* @param {function} encodeFileName 针对注释是否进行编码const iconv = require('iconv-lite') encodeFileName: function (string) { return iconv.encode(string, 'your-encoding')}
* @param {Boolean} streamFiles 默认false,指定是否使用流式处理文件,设置为true时JSZip会在读取或写入zip文件时使用流式处理,针对处理大型zip文件或需要逐步处理文件时有用
* @param {function} onUpdate 回调函数,用于监控不过zip文件的创建或解压缩过程的进度,该回调函数会在每个文件完成处理时调用,回调参数为当前进度的百分比
*/
// 压缩方法1
zip.generateAsync({ type: 'blob', compression: 'DEFLATE' }).then(content => {
// 配合使用file-saver进行保存
saveAs('content', 'example.zip')
// 变为可上传的文件
const uploadFile = new File([content], 'example.zip')
})
// 压缩方法2
zip.generateAsync({type:"base64"})
.then(function (content) {
location.href="data:application/zip;base64,"+content;
})
// 压缩方法3
zip.folder("folder_1").folder("folder_2").file("hello.txt", "hello");
// zip now contains:
// folder_1/
// folder_1/folder_2/
// folder_1/folder_2/hello.txt
zip.folder("folder_1").generateAsync({type:"nodebuffer"})
.then(function (content) {
// relative to folder_1/, this file only contains:
// folder_2/
// folder_2/hello.txt
require("fs").writeFile("hello.zip", content, function(err){/*...*/});
});