一、安裝依賴
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