後端返回的是文件流,需要前端轉換成Excel文件並下載到本地,具體寫法如下:
axios.post('/api/export', qs.stringify(params), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded', //請求的數據類型爲form data格式
},
'responseType': 'blob' //設置響應的數據類型爲一個包含二進制數據的 Blob 對象,必須設置!!!
}).then(function (response) {
const blob = new Blob([response.data]);
const fileName = 'xxx.xls';
const linkNode = document.createElement('a');
linkNode.download = fileName; //a標籤的download屬性規定下載文件的名稱
linkNode.style.display = 'none';
linkNode.href = URL.createObjectURL(blob); //生成一個Blob URL
document.body.appendChild(linkNode);
linkNode.click(); //模擬在按鈕上的一次鼠標單擊
URL.revokeObjectURL(linkNode.href); // 釋放URL 對象
document.body.removeChild(linkNode);
}).catch(function (error) {
console.log(error);
});
按照網上的一些寫法,但是請求時都沒有加上responseType:blob,出現的錯誤類型:
- 導出的文件亂碼
const blob = new Blob([response.data])
寫成
const blob = new Blob([response.data],{type: 'application/vnd.ms-excel'})
導出的文件打開,顯示爲[object Object]
所以,解決亂碼問題的關鍵就是請求時加上 ‘responseType’: 'blob’
附上 Blob 對象的詳細介紹:
https://segmentfault.com/a/1190000011563430