引言
通過 window.open(url) 的方法下載文件战坤,需要打開一個新的頁面下載,影響用戶體驗福稳。
且如果參數(shù)數(shù)據(jù)量大涎拉,用 url 掛參的方式也不方便。
用 post 下載文件的圆,即可解決上述問題鼓拧,優(yōu)雅而美麗!
后端
后端需要將下載的接口的response header設(shè)置以下:
Content-disposition: attachment; filename=name.xlsx
Content-Type:application/octet-stream
1
2
前端
前端需修改 axios 請求的 responseType 為blob越妈,或者arrayBuffer季俩,具體看數(shù)據(jù)格式,然后創(chuàng)建 a 標(biāo)簽叮称,模擬 a 標(biāo)簽點擊:
axios({
method: 'post',
url: '接口地址',
data: formData,// 提交的數(shù)據(jù)
responseType: 'blob'
}).then(response => {
let data=response.data // 根據(jù)返回拿到 Blob 的數(shù)據(jù)
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a') // 創(chuàng)建<a>標(biāo)簽
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'name.xlsx')
document.body.appendChild(link)
link.click() // 模擬點擊<a>標(biāo)簽
}).catch((error) => {
console.log(error)
})
結(jié)語
再也不要 window.open 啦种玛!