【Vue】基于vue3封装批量下载功能
一、安装依赖
npm install jszip npm install file-saver
二、代码实现
import axios from 'axios' import JSZip from 'jszip' import FileSaver from 'file-saver'; /** * 批量下载 * @param {Object} fileList */ export function downloadFileList(fileList, fileName) { // 初始化 const zip = new JSZip(); const promises = fileList.map((fileUrl, index) => { return new Promise((resolve, reject) => { axios({ method: 'get', url: fileUrl, responseType: 'arraybuffer', }) .then(res => { // 下载文件, 并存成ArrayBuffer对象 const cleanUrl = fileUrl.split('?')[0]; const idx = cleanUrl.lastIndexOf("/"); const fileName = cleanUrl.substring(idx+1); // 逐个添加文件 zip.file(fileName, res.data, { binary: true }); resolve(); }) .catch(err => { reject('加载失败:' + err) }) }) }) return Promise.all(promises) .then(res => { zip.generateAsync({ type: 'blob' }).then(content => { FileSaver.saveAs(content, fileName + '_' + new Date().getTime() + '.zip') }) }) }
参考文献:https://blog.csdn.net/weixin_49053419/article/details/135291594
得意时做事,失意时读书