//link.target=“_blank”;
elink.click()
}
由于a.download跨域会失效,上面代码只可同域实现
二、通过blob实现跨域下载并修改文件名(同样适用于URL地址)
方法
//通过文件下载url拿到对应的blob对象
getBlob(url) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest()
xhr.open(‘GET’, url, true)
xhr.responseType = ‘blob’
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response)
}
}
xhr.send()
})
},
//下载文件 js模拟点击a标签进行下载
saveAs(blob, filename) {
var link = document.createElement(‘a’)
link.href = window.URL.createObjectURL(blob)
link.download = filename
link.click()
},
事件调用
<a-button type=“primary” icon=“download” @click=“downFile”>下载
//文件下载
downFile() {
let fileUrl = imgView + ‘group1/M00/00/88/FGQfoGIPDfuAErRaAABGAH4FyJ4422.xls’ //服务器文件地址
this.getBlob(fileUrl).then(blob => {
this.saveAs(blob, ‘信用权证使用导入模板件名.xlsx’)
})
},
以上是直接拿文件url地址下载。
请求接口下载文件方法: 以下方法仅供参考,项目不同,调用方法不同
vue组件
import { exportxlsx } from ‘@/api/api’
//导出
exportData() {
let req = {
createStartDate: this.startDate,
createEndDate: this.endDate,
status: this.status,
}
exportxlsx(‘/sys/mjBaseCount/exportMjGuaCountData’, req).then(res => {
console.log(res);
this.loading = false
const content = res
const blob = new Blob([content])
const fileName = ‘担保方式统计.xlsx’
if (‘download’ in document.createElement(‘a’)) {
// 非IE下载
const elink = document.createElement(‘a’)
elink.download = fileName
elink.style.display = ‘none’
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName)
}
})
}
api.js文件
import { exportFunc } from ‘@/api/manage’
//导出
const exportxlsx = (url, params) => {
params.brNo = “000000”
最后
喜欢的话别忘了关注、点赞哦~
开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】