[TOC]
[jszip官网](https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html)
### 1. 安装
~~~
npm install jszip
yarn add jszip // 亲测有效
~~~
### 2. 引入
~~~
import JSZip from 'jszip';
import * as JSZip from 'jszip'; // 亲测有效
~~~
### 3. 使用
~~~
let zipFile: JSZip = new JSzip();
~~~
### 4. 示例
[示例1](https://codepen.io/a631807682/pen/EMEKoL?editors=1011)
~~~
function zipFiles(dom){
let zip = new JSZip();
for(let f of dom.files){
zip.file(f.webkitRelativePath, f);
}
zip.generateAsync({type:"blob"})
.then(function (blob) {
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'test.zip';
link.click();
});
}
~~~
示例2
~~~
// webkitdirectory控制是否为上传文件夹
type="file"
class="add-file-input"
v-if="dataForm.type === 'GDB' || dataForm.type === 'SHAPE'"
@change="zipFiles"
multiple="multiple"
webkitdirectory
/>
// 上传文件夹、多选文件打包上传
zipFiles(e) {
const { files } = e.target
let flag = false
const zip = new JSZip()
for (let index = 0; index < files.length; index++) {
files[index].webkitRelativePath && zip.file(files[index].webkitRelativePath, files[index])
// 判断是否包含shp文件
if (files[index].name.slice(-4) === '.shp') {
flag = true
}
}
const arrPath = files[0].webkitRelativePath.split('/')
if (
(arrPath[0].slice(-4) === '.gdb' && this.dataForm.type === 'GDB') ||
(flag && this.dataForm.type === 'SHAPE')
) {
// return promise对象 该方法是异步方法
zip.generateAsync({ type: 'Blob', compression: 'DEFLATE' }).then(content => {
// 创建file对象
const fils = new File([content], arrPath[0], { type: 'zip' })
// console.log(fils)
this.file.fileData = fils
this.dataForm.name = fils.name
this.dataForm.connection.Path = `${fils.name}.zip`
})
} else {
this.$message.error(`上传文件格式应为${this.dataForm.type}类型!`)
this.file.fileData = ''
this.dataForm.name = ''
this.dataForm.connection.Path = ''
}
},
~~~
[示例3](https://www.cnblogs.com/dearxinli/p/8422140.html)
[示例4](https://blog.csdn.net/qq2523208472/article/details/83578722)