vue跳转url地址下载文件时如何给文件添加header信息(比如:token)
vue跳转url地址下载文件时如何给文件添加header信息(比如:token)
·
需求背景:在项目中,通过url跳转链接(location.href或者<a>标签)都可以实现文件下载功能,若需要跳转url时,请求此url接口,目的携带token等请求头信息,则无法通过href等跳转下载,下文主要解决次情况。
1、通过href跳转下载:
async exportForm() {
let url =
process.env.VUE_APP_BASE_API +
'/api/compare/xxx/xxx/xx/xx?参数信息
location.href = url
},
2、携带token请求接口,下载文件
async exportForm() {
const res = await exportList() //请求url接口
const dowmName=res.headers['content-type'].split('.')[0] //获取下载文件名称(在请求头中)
const url = window.URL.createObjectURL(new Blob([res.data]))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute(
'download',
`${dowmName}.xlsx`
)
document.body.appendChild(link)
link.click()
},
res返回信息如图:
接口信息(必写:responseType: 'blob'):
获取请求头信息:
更多推荐
已为社区贡献6条内容
所有评论(0)