vue jszip file-saver 实现一个勾选,批量前端下载文件,多个的话进行下载zip文件下载功能,如下图所示
1. 安装依赖
npm install jszip
npm install file-saver
2. 在utils文件下新建downloadZip.js 封装下载zip包方法
downloadZip.js 文件代码
import axios from "axios"
import JSZip from "jszip"
import FileSaver from "file-saver"
export const downloadZip = {
handleBatchDownload(data) {
const zip = new JSZip()
const cache = {}
const promises = []
let _this = this
data.forEach((item) => {
const promise = _this.getFile2(item.url).then((data) => {
zip.file(item.file_name, data, {
binary: true,
})
cache[item.file_name] = data
})
promises.push(promise)
})
Promise.all(promises).then(() => {
zip
.generateAsync({
type: "blob",
})
.then((content) => {
FileSaver.saveAs(content, "批量下载.zip")
})
})
},
getFile2(url) {
return new Promise((resolve, reject) => {
axios({
method: "get",
url,
responseType: "arraybuffer",
})
.then((data) => {
resolve(data.data)
})
.catch((error) => {
reject(error.toString())
})
})
},
}
3. vue 页面调用 handleBatchDownload 方法进行下载
先vue页面引用方法
import { downloadZip } from "@/utils/downloadZip"
点击下载进行下载保存,如下
downLoadAll(){
let data = [
{
url:'https://profile.csdnimg.cn/8/1/5/1_qq_36410795',
file_name:'2022-04-11-日志.pdf'
},
{
url:'https://profile.csdnimg.cn/8/1/5/1_qq_36410795',
file_name:'2022-04-14-日志.pdf'
}
]
await downloadZip.handleBatchDownload(data)
}
|