效果图
1、安装jszip和file-saver插件
npm install jszip
npm install file-saver
2、在所需页面引入
import JSZip from "jszip";
import FileSaver from "file-saver";
3、模拟fileList数组
//fileList模拟文件数组export default {name: "notice-list",data() {return {fileList: [{originalName: '3.jpg',url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'},{originalName: '5.jpg',url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'},{originalName: '测试2.doc',url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'}],}}
}
4、在methods中定义方法
//批量下载文件batchDownload() {var blogTitle = `附件_${new Date().getTime()}`; // 下载后压缩包的名称var zip = new JSZip();var promises = [];let cache = {};for (let item of this.fileList) {// item.url为文件链接地址// item.originalName为文件名称if (item.url) {const promise = this.getImgArrayBuffer(item.url).then((data) => {// 下载文件, 并存成ArrayBuffer对象(blob)zip.file(item.originalName, data, { binary: true }); // 逐个添加文件cache[item.originalName] = data;});promises.push(promise);} else {// url地址不存在时提示this.$message.error(`附件${item.originalName}地址错误,下载失败`);console.log(`附件${item.originalName}地址错误,下载失败`);}}Promise.all(promises).then(() => {zip.generateAsync({ type: "blob" }).then((content) => {// 生成二进制流FileSaver.saveAs(content, blogTitle); // 利用file-saver保存文件 blogTitle:自定义文件名});}).catch((res) => {this.$message.error("文件压缩失败");});},//文件以流的形式获取(参数url为文件链接地址)getImgArrayBuffer(url) {return new Promise((resolve, reject) => {//通过请求获取文件blob格式let xmlhttp = new XMLHttpRequest();xmlhttp.open("GET", url, true);xmlhttp.responseType = "blob";xmlhttp.onload = function () {if (xmlhttp.status == 200) {resolve(xmlhttp.response);} else {reject(xmlhttp.response);}};xmlhttp.send();});},