首先我们要在vue项目里安装下载jszip、file-saver依赖
npm install jszip npm install file-saver (或者 yarn i jszip yarn i file-saver)
<template> <span @click="onDownAllSign">下载压缩包</span> </template> <script> import JSZip from "jszip"; import FileSaver from "file-saver"; import {$local} from "../lib/local"; const getFile = url => { return new Promise((resolve, reject) => { axios({ method: "get", url, responseType: "arraybuffer" }).then(data => { resolve(data.data); }).catch(error => { reject(error.toString()); }); }); }; export default { data() { return { dataId: [] } }, methods: { //批量导出 async onDownAllSign() { let info = { userId: $local.getItem('userId'), courseId: $local.getItem('courseId'), search: '' } let {data} = await this.$fetch('接口地址', info) data.sign.forEach((item) => { let obj = { id: item.id, title: item.title } this.dataId.push(obj) }) this.downLoad(this.dataId) }, downLoad(info) { const data = info; const zip = new JSZip(); const cache = {}; const promises = []; data.forEach(item => { var baseURL= process.env.BASE_API.indexOf('http') !== -1 ? process.env.BASE_API : window.location.origin + '/api' var url = baseURL + '/goods/distributionGoodsWxaCodeStream?item_id=' + item.itemId const promise = getFile(url).then(result_file => { // 下载文件, 并存成ArrayBuffer对象 const file_name = item.title + '.xls' // 获取文件名 zip.file(file_name, result_file, {binary: true}) // 逐个添加文件 cache[file_name] = data; }); promises.push(promise); }); Promise.all(promises).then(() => { zip.generateAsync({type: "blob"}).then(content => { // 生成二进制流 FileSaver.saveAs(content, "考勤.zip"); // 利用file-saver保存文件 自定义文件名 }); }); } } } </script>