vue3多文件下载zip文件包
效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/51089bb8d5614cba8dd34c3f244809f3.png)
代码块
在这里插入代码片
<template>
<div>
<el-button type="primary" @click="downLoadClick">下载文件zip</el-button>
</div>
</template>
<script setup lang="ts">
import JSZip from "jszip";
const fileUrls = [
"https://xxxx.aliyuncs.com/erp-test-upload/note/2024/07/14/1/18123873099490877141/消息通知-未读-20240711185838.xlsx",
"https://xxxx.aliyuncs.com/erp-test-upload/note/2024/07/14/1/1812387309907144404/th.jpg"
];
const zip = new JSZip();
const downLoadClick = async () => {
try {
await fileSteam(fileUrls);
const blob = await zip.generateAsync({type: 'blob'});
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'files.zip';
a.click();
window.URL.revokeObjectURL(url);
} catch (error) {
console.error('生成压缩包或下载过程中发生错误:', error);
}
};
const fileSteam = async (urls: string[]) => {
const promises = urls.map(async (url) => {
try {
const response = await fetch(url);
const blob = await response.blob();
const arrayBuffer = await blob.arrayBuffer();
const fileName = url.split('/').pop();
zip.file(fileName || 'file', new Uint8Array(arrayBuffer));
} catch (error) {
console.error(`Fetch file from ${url} failed:`, error);
}
});
await Promise.all(promises);
};
</script>