以下未axios,vue導出后台文件流形式Excel
這次的需求是導出excel表格,但不是給你返回網絡路徑。而是以文件流的形式返回一串亂碼的玩意兒。看不懂。
以前沒接觸過這種東西,只是聽說過后台可以文件流返回而今天一看卻是懵逼的狀態。
項目使用vue+axios 和element ui
使用post請求做到自下載。
下文代碼 ``` exportData () { const form = this.getSearchForm() // 要發送到后台的數據 axios({ // 用axios發送post請求 method: 'post', url: '/user/12345', // 請求地址 data: form, // 參數 responseType: 'blob' // 表明返回服務器返回的數據類型 }) .then((res) => { // 處理返回的文件流 const content = res const blob = new Blob([content]) const fileName = '測試表格123.xls' if ('download' in document.createElement('a')) { // 非IE下載 const elink = document.createElement('a') elink.download = fileName elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() URL.revokeObjectURL(elink.href) // 釋放URL 對象 document.body.removeChild(elink) } else { // IE10+下載 navigator.msSaveBlob(blob, fileName) } }) } ``` // 一定要看到 responType:'blob' ``` axios.post(url,data,{responseType:'blob'}) 這樣死活就是不行 ``` ``` axios({ method: 'post', url: '/user/12345', // 請求地址 data: form, // 參數 responseType: 'blob' // 表明返回服務器返回的數據類型 }) .then((response)=>{ const blob = new Blob([response]) const fileName = '測試表格123.xls' if ('download' in document.createElement('a')) { // 非IE下載 const elink = document.createElement('a') elink.download = fileName elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() URL.revokeObjectURL(elink.href) // 釋放URL 對象 document.body.removeChild(elink) } else { // IE10+下載 navigator.msSaveBlob(blob, fileName) } })
```