vue+axios實現文件下載
功能:點擊導出按鈕,提交請求,下載excel文件;
第一步:跟后端童鞋確認交付的接口的response header設置了
![]()
以及返回了文件流。
第二步:修改axios請求的responseType為blob,以post請求為例:
axios({
method: 'post',
url: 'api/user/',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
responseType: 'blob'
}).then(response => {
this.download(response)
}).catch((error) => {
})
第三步:請求成功,拿到response后,調用download函數(創建a標簽,設置download屬性,插入到文檔中並click)
methods: {
// 下載文件
download (data) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'excel.xlsx')
document.body.appendChild(link)
link.click()
}
}

