npm install jszip
npm install file-saver
import JSZip from "jszip";
import FileSaver from "file-saver";
import {Message} from "view-design";
/**
* 下载文件 传数组
* fileList
* [
* {
* type:'file',
* name:'17034953113790548.png',
* url:'https://zwdev.oss-cn-beijing.aliyuncs.com/company_1/default/17034953113790548.png',
* },
* {
* type:'folder',
* name:'图片',
* children:[
* {
* type:'file',
* name:'17034953113790548.png',
* url:'https://zwdev.oss-cn-beijing.aliyuncs.com/company_1/default/17034953113790548.png',
* },
* ]
* }
* ]
* @param {*} fileList
* @param fileName //zip文件名称 默认时间戳
*/
export function downLoadZip(fileList, fileName = new Date().getTime()) {
const zip = new JSZip()
const promises = []
fileList.forEach((item, index) => {
if (item.type === 'folder') {
let promiseFolder = zip.folder(item.name)//文件夹名
if (item.children && item.children.length > 0) {
item.children.forEach((file, ii) => {
let promise = getFile(file.url).then((data) => {
promiseFolder.file(file.name, data, {binary: true})//文件名、文件流、是否为二进制
})
promises.push(promise)
})
}
} else if (item.type === 'file') {
let promise = getFile(item.url).then((data) => {
zip.file(item.name, data, {binary: true})//文件名、文件流、是否为二进制
})
promises.push(promise)
}
})
Promise.all(promises).then(() => {
zip.generateAsync({type: 'blob'}).then((content) => {
//利用file-saver保存文件 自定义文件名
FileSaver.saveAs(content, fileName)
})
}).catch((err) => {
Message.error({content: '文件压缩失败' + err})
})
}
function getFile(url) {
return new Promise((resolve, reject) => {
//通过请求获取文件blob格式
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.responseType = "blob";
xmlhttp.onload = function () {
if (this.status == 200) {
resolve(this.response);
} else {
reject(this.status);
}
}
xmlhttp.send();
});
}