需要的功能是批量下载并压缩xlsx文件,后端传给我的数据是下载链接。网络上搜索到的都是用promise解决异步获取文件的问题,但是我使用时候会出现文件错乱互相覆盖(原因是啥我也没研究明白),导致下载的文件名对,文件内容不对的诡异情况,研究过后只能轮询转化,即一次转换文件成功后再重新循环转化。
首先是依赖包的下载,用到的是JSZip和FileSaver
npm install jszip
npm install file-saver
然后在自己封装方法的文件夹里创建一个js文件zipBatch.js,内容如下:
import JSZip from "jszip";
import FileSaver from "file-saver";//引入依赖包
let zipBatch = {};//方法名,调用时候用
let fileIndex = 0; //轮循脚标,轮循一次,fileIndex++
let fileList = []; //存放转化完成的文件的数组
let arrSource = []; //原始数据
let blogTitle = ''; //压缩包的名称
zipBatch.zip = (arr,title) =>{
//参数arr是原始数据,每个元素两个属性 path 文件链接 ,title 文件名称
//参数title是压缩完成的压缩包名
fileList = [];
arrSource = arr;
blogTitle = title;
fileIndex = 0;
zipBatch.addLoop();
}
zipBatch.addLoop = () =>{
let submitIndex = fileIndex;
if (submitIndex >= arrSource.length) { //轮询结束开始压缩
var zip = new JSZip();
var promises = [];
fileList.forEach(item => {
let file_name = item.title + '.xlsx' //若下载其他文件此处后缀名就改成其他后缀名
zip.file(file_name, item.binary, { binary: true }); // 逐个添加文件
})
zip.generateAsync({ type: "blob" }).then((content) => {
// 生成二进制流
FileSaver.saveAs(content, blogTitle); // 利用file-saver保存文件 blogTitle:自定义文件名
});
return;
}
let item = arrSource[submitIndex];
zipBatch.addCore( item, function () {
fileIndex++;
zipBatch.addLoop();
});
}
zipBatch.addCore = (item, finallyFun) =>{
//文件以流的形式获取
// 方法1
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", item.path, true);
xmlhttp.responseType = "blob";
// xmlhttp.setRequestHeader("Content-type", "application/json")
xmlhttp.onload = function () {
if (xmlhttp.status == 200) {
fileList.push({
binary: xmlhttp.response, // 文件
title: item.title // 文件名称
})
finallyFun()
} else {
// 获取失败处理
}
};
xmlhttp.send();
// 方法2
// fetch(item.path).then((response) => response.blob())
// .then((blob) => {
// //将blob对象转换为file并返回
// let file = new File([blob], title, {type: blob.type, lastModified: Date.now()});
// fileList.push({
// binary: file, // 文件链接
// title: item.path // 文件名称
// })
// })
}
export default zipBatch;
在页面引用此方法
import zipBatch from '@/libs/zipBatch.js';
获取到数据以后拼成可用的数据源,然后调用方法
downloadBtn() {
let title = '报表'; // 下载后压缩包的名称
let arrSource = [];
//拼接数据源
this.statementList.forEach((item, index) => {
arrSource.push({
path: item.url, // 文件链接
title: item.title // 文件名称
})
})
zipBatch.zip(arrSource, title)
}
触发downloadBtn方法,就可以下载statementList存放的数据了。