vue3 多文件批量下载
时间: 2023-12-01 12:42:09 浏览: 116
以下是使用Vue3实现多文件批量下载的代码示例:
```html
<template>
<div>
<button @click="downloadFiles">下载文件</button>
</div>
</template>
<script>
import axios from 'axios';
import JSZip from 'jszip';
import FileSaver from 'file-saver';
export default {
data() {
return {
fileUrls: [
'https://example.com/file1.pdf',
'https://example.com/file2.jpg',
'https://example.com/file3.docx'
]
};
},
methods: {
async downloadFiles() {
const zip = new JSZip();
const promises = [];
// 下载文件并添加到zip中
this.fileUrls.forEach((url, index) => {
const promise = axios.get(url, { responseType: 'blob' })
.then(response => {
const fileName = `file${index + 1}.${response.data.type.split('/')[1]}`;
zip.file(fileName, response.data);
});
promises.push(promise);
});
// 等待所有文件下载完成后生成zip并下载
Promise.all(promises).then(() => {
zip.generateAsync({ type: 'blob' }).then(content => {
FileSaver.saveAs(content, 'files.zip');
});
});
}
}
};
</script>
```
阅读全文