背景:现接口存在多个媒体文件(图片、视频、音频)的集合,要求实现单个下载和多个批量下载。
思考:对于此需求以后可能会一个项目碰到多次下载
直接上代码
一:单个下载
// v-for循环出来的dom,此处只展示按钮。其余显示图片等不做代码展示
<span class="mar_left color_lan" @click="downLoadOnce(item)">下载</span>
// 单个下载
import { downFile, doenOnce } from '../../utils'
const downLoadOnce = (val: any) => {
doenOnce(val.fileUrl, val.fileName, val.type)
}
二:批量下载
<el-button class="btn" type="primary" size="large" plain @click="downLoad">下载</el-button>
import { downFile, doenOnce } from '../../utils'
// 批量下载
const downLoad = () => {
let list: any = []
imageList.value.forEach((item: any) => {//imageList源list文件
if (item.ischeck) {// 找出勾选的有哪些
list.push(item)
}
})
if (list.length === 0) {
ElMessage({
type: 'info',
message: '请至少选择一个文件下载',
})
return
}
downFile(list)
}
下面是util封装的公共类
const getFile = (url: any) => {
return new Promise((resolve, reject) => {
axios({
method: 'get',
url,
responseType: 'arraybuffer',
})
.then(data => {
resolve(data.data)
})
.catch(error => {
reject('加载失败:' + error)
})
// resolve(getBase64Image(url));
})
}
const downFile = async (arrList: any) => {
console.log(arrList)
const zip = new JSZip()
const cache: any = {}
const promises: any = []
await arrList.forEach((item: any) => {
const promise = getFile(item.fileUrl + '?=' + Math.random()).then((data: any) => {
// 下载文件, 并存成ArrayBuffer对象
const lst = item.fileUrl.split('.')
const fileType = lst[lst.length - 1]
console.log(fileType)
zip.file(item.fileName + '.' + fileType, data, { binary: true }) // 逐个添加文件
cache[item.fileName] = data
})
promises.push(promise)
})
Promise.all(promises).then(() => {
zip.generateAsync({ type: 'blob' }).then(content => {
// 生成二进制流
FileSaver.saveAs(content, '模板下载.zip') // 利用file-saver保存文件
})
})
}
// 单个下载
const doenOnce = (url: any, name: any, type: any) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url + '?=' + Math.random(), true)
xhr.responseType = 'arraybuffer' // 返回类型blob
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const blob = this.response
// 转换一个blob链接
const lst = url.split('.')
const fileType = lst[lst.length - 1]
console.log(fileType)
let u
if (type === 'image') {
u = window.URL.createObjectURL(new Blob([blob], { type: 'image/png' })) // 视频的type是video/mp4,图片是image/jpeg
} else {
u = window.URL.createObjectURL(new Blob([blob], { type: 'video/mp4' })) // 视频的type是video/mp4,图片是image/jpeg
}
const a = document.createElement('a')
a.download = name // 设置下载的文件名
a.href = u
a.style.display = 'none'
document.body.appendChild(a)
a.click()
a.remove()
}
}
xhr.send()
}
export { downFile, doenOnce }