效果:一键下载打开了PDF文件和dox
问题: 连续打开window.open 会被拦截
方案如下:

交互效果 会有下载多个文件的提示

代码:

注意: 单独处理pdf , 不然会出现只能打开pdf 或最后一个
arr.forEach((url, index) => {
if (url.indexOf('.pdf') != -1) { // pdf文件域名不能跨域
this.axiosDownload(url)
} else {
setTimeout(() => {
let a = document.createElement('a') // 创建a标签
let e = document.createEvent('MouseEvents') // 创建鼠标事件对象
e.initEvent('click', false, false) // 初始化事件对象
a.href = url // 设置下载地址
a.download = 'shangma' // 设置下载文件名
a.dispatchEvent(e)
}, 500 * index)
}
})
ajax请求的域名要可以跨域
axiosDownload(url) {
this.$axios({
url,
method: 'GET',
responseType: 'blob' // important
}).then(data => {
const dom = document.createElement('a')
dom.href = window.URL.createObjectURL(new Blob([data]))
dom.setAttribute('download', url.match(/[^/]+$/))
document.body.appendChild(dom)
dom.click()
setTimeout(() => {
window.URL.revokeObjectURL(url)
document.body.removeChild(dom)
}, 0)
})
},
参考文章
参考文章2