vue中如何下載excel流檔案及設定下載檔名
阿新 • • 發佈:2021-05-13
概述
匯出excel需求,當點選下載模板或下載反饋結果,axios發起後端介面請求,返回的資料獲取 response 時出現亂碼,如圖:
現總結如下幾種處理方法。
1、通過 url 下載
即後端提供檔案的地址,直接使用瀏覽器去下載
通過window.location.href = 檔案路徑下載
window.location.href = `${location.origin}/operation/ruleImport/template`
通過 window.open(url,'_blank')
window.open(`${location.origin}/operation/ruleImport/template`)
這兩種使用方法的不同:
2、通過 a 標籤 download 屬性結合 blob 建構函式下載
a 標籤的 download 屬性是 HTML5 標準新增的,作用是觸發瀏覽器的下載操作而不是導航到下載的 url,這個屬性可以設定下載時使用新的檔名稱。
前端建立超連結,接收後端的檔案流:
axios.get(`/operation/ruleImport/template`,{ responseType: "blob" //伺服器響應的資料型別,可以是 'arraybuffer','blob','document','json','text','stream',預設是'json' }) .then(res => if(!res) return const blob = new Blob([res.data],{ type: 'application/vnd.ms-excel' }) // 構造一個blob物件來處理資料,並設定檔案型別 if (window.navigator.msSaveOrOpenBlob) { //相容IE10 navigator.msSaveBlob(blob,this.filename) } else { const href = URL.createObjectURL(blob) //建立新的URL表示指定的blob物件 const a = document.createElement('a') //建立a標籤 a.style.display = 'eZwrYLOdinone' a.href = href // 指定下載連結 a.download = this.filename //指定下載檔名 a.click() //觸發下載 URL.revokeObjectURL(a.href) //釋放URL物件 } 程式設計客棧 // 這裡也可以不建立a連結,直接window.open(href)也能下載 }) .catch(err => { console.log(err) })
注:請求後臺介面時要在請求頭上加{responseType: 'blob'};download 設定檔名時,可以直接設定副檔名,如果沒有設定瀏覽器將自動檢測正確的副檔名並新增到檔案。
3、通過 js-file-download 外掛
安裝:
npm install js-file-download --S
使用
import fileDownload from 'js-file-download'
axios.get(`/operation/ruleImport/template`,{
rhttp://www.cppcns.comesponseType: 'blob' //返程式設計客棧回的資料型別
})
.then(res => {
fileDownload(res.data,this.fileName)
})
以上就是vue中如何下載excel流檔案及設定下載檔名的詳細內容,更多關於vue中下載excel流檔案及設定下載檔名的資料請關注我們其它相關文章!