封装Window.open,报错不停留在空白页面
在项目开发运行中,不论是测试环境还是正式,都不想在下载文件时报错停留在空白页面,导致用户体验差的情况。查看了百度各种方法,有用Blod写的,有用axios获取的,但是没有一个可用。。。为此,me“连夜”设计了如下代码,实现上方的需求,有需要的小伙伴可自行领取。(当然,只适用于文件名称是后端返回的,前端无需操作的情况)
话不多说,上代码
// 导出/下载模板
function downLoadFileFromUrl(address,mode,colseLoading){
return new Promise((resolve,reject)=>{
axios({
url: address,
method: mode,
responseType: 'blob', }
})
.then(res => {
if (!res.data) {
return
}
var fileName = res.headers['content-disposition'].match(/(filename=)(.*?)$/)[2].replace(/"/g, '')
let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.ms-excel' }))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.download=decodeURIComponent(fileName)
document.body.appendChild(link)
link.click()
// 释放URL对象所占资源
window.URL.revokeObjectURL(url)
// 用完即删
document.body.removeChild(link)
// colseLoading(res)
// if (res.data.code == '002') {
// colseLoading(res)
// }
})
.catch(res => {
colseLoading(res)
})
})
}
复制完成后,不要忘记在代码里添加本地的token,在点击下载按钮时,传入具体参数,就可以使用啦,
好啦,用到就点个赞吧