post下载

2021-04-22  本文已影响0人  动感光波波波

引言
通过 window.open(url) 的方法下载文件,需要打开一个新的页面下载,影响用户体验。

且如果参数数据量大,用 url 挂参的方式也不方便。

用 post 下载文件,即可解决上述问题,优雅而美丽!

后端
后端需要将下载的接口的response header设置以下:

Content-disposition: attachment; filename=name.xlsx
Content-Type:application/octet-stream
1
2
前端
前端需修改 axios 请求的 responseType 为blob,然后创建 a 标签,模拟 a 标签点击:

axios({
method: 'post',
url: '接口地址',
data: formData,// 提交的数据
responseType: 'blob'
}).then(response => {
let data=response.data // 根据返回拿到 Blob 的数据
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a') // 创建<a>标签
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'name.xlsx')
document.body.appendChild(link)
link.click() // 模拟点击<a>标签
}).catch((error) => {
console.log(error)
})

结语
再也不要 window.open 啦!

上一篇下一篇

猜你喜欢

热点阅读