需要的两个依赖 1. file-saver 2. jszip
import { saveAs } from 'file-saver'
import JSZip from 'jszip'
import ElementUI from 'element-ui'
function getFile(url) {
return new Promise((resolve, reject) => {
// 通过请求获取文件blob格式 用axios发起下载请求跨域(只要不出跨域问题jquery或者axios什么的请求都是可以的)
const xmlhttp = new XMLHttpRequest()
xmlhttp.open('GET', url, true)
xmlhttp.responseType = 'blob'
xmlhttp.onload = function() {
if (this.status === 200) {
resolve(this.response)
} else {
reject(this.status)
}
}
xmlhttp.send()
})
}
/**
* 下载批量文件的压缩包
* @param urlList 组成dome [{url:'文件路径', name: '文件名称'}]
* @param zipName 压缩文件名称
* @param suffix 压缩的每个文件的扩展名 例如:docx
*/
export function downFileZip(urlList, zipName, suffix) {
if (!urlList || urlList.length < 1) {
ElementUI.Message({
message: '请选择需要下载的数据!',
type: 'error'
})
return
}
zipName = zipName || '下载文件压缩包'
const zip = new JSZip()
// cache只是用于检查数据的 并没有任何实际意义
const cache = {}
const promises = []
// urlList附件url地址数组
urlList.forEach(item => {
// 下载文件
const promise = getFile(item.url).then(data => {
// 逐个添加文件 追加文件后缀
zip.file(`${item.name}.${suffix}`, data, { binary: true })
cache[item.name] = data
})
promises.push(promise)
})
// 异步队列全部完成时 执行下面代码
Promise.all(promises).then(() => {
// 生成二进制流
zip.generateAsync({ type: 'blob' }).then(content => {
// 利用file-saver保存文件
saveAs(content, `${zipName}.zip`)
})
})
}
/**
* 批量下载文件
* @param urlList 组成dome ['路径']
*/
export function downBatchFile(urlList) {
if (!urlList || urlList.length < 1) {
ElementUI.Message({
message: '请选择需要下载的数据!',
type: 'error'
})
return
}
for (let i = 0; i < urlList.length; i++) {
const hiddenIFrameID = 'hiddenDownloader' + i
const iframe = document.createElement('iframe')
iframe.id = hiddenIFrameID
iframe.style.display = 'none'
document.body.appendChild(iframe)
// 直接下载,不会弹出新的页面
iframe.src = urlList[i]
// 销毁iframe
setTimeout(function() {
iframe.remove()
}, 60 * 1000)
}
}