vue中如何下載excel流文件及設(shè)置下載文件名
導(dǎo)出excel需求,當(dāng)點擊下載模板或下載反饋結(jié)果,axios發(fā)起后端接口請求,返回的數(shù)據(jù)獲取 response 時出現(xiàn)亂碼,如圖:
現(xiàn)總結(jié)如下幾種處理方法。
1、通過 url 下載即后端提供文件的地址,直接使用瀏覽器去下載
通過window.location.href = 文件路徑下載
window.location.href = `${location.origin}/operation/ruleImport/template`
通過 window.open(url, ’_blank’)
window.open(`${location.origin}/operation/ruleImport/template`)
這兩種使用方法的不同:
window.location:當(dāng)前頁跳轉(zhuǎn),也就是重新定位當(dāng)前頁;只能在網(wǎng)站中打開本網(wǎng)站的網(wǎng)頁。 window.open:在新窗口中打開鏈接;可以在網(wǎng)站上打開另外一個網(wǎng)站的地址。2、通過 a 標(biāo)簽 download 屬性結(jié)合 blob 構(gòu)造函數(shù)下載a 標(biāo)簽的 download 屬性是 HTML5 標(biāo)準(zhǔn)新增的,作用是觸發(fā)瀏覽器的下載操作而不是導(dǎo)航到下載的 url,這個屬性可以設(shè)置下載時使用新的文件名稱。
前端創(chuàng)建超鏈接,接收后端的文件流:
axios.get(`/operation/ruleImport/template`, {responseType: 'blob' //服務(wù)器響應(yīng)的數(shù)據(jù)類型,可以是 ’arraybuffer’, ’blob’, ’document’, ’json’, ’text’, ’stream’,默認(rèn)是’json’ }) .then(res => if(!res) returnconst blob = new Blob([res.data], { type: ’application/vnd.ms-excel’ }) // 構(gòu)造一個blob對象來處理數(shù)據(jù),并設(shè)置文件類型if (window.navigator.msSaveOrOpenBlob) { //兼容IE10 navigator.msSaveBlob(blob, this.filename)} else { const href = URL.createObjectURL(blob) //創(chuàng)建新的URL表示指定的blob對象 const a = document.createElement(’a’) //創(chuàng)建a標(biāo)簽 a.style.display = ’none’ a.href = href // 指定下載鏈接 a.download = this.filename //指定下載文件名 a.click() //觸發(fā)下載 URL.revokeObjectURL(a.href) //釋放URL對象}// 這里也可以不創(chuàng)建a鏈接,直接window.open(href)也能下載 }) .catch(err => {console.log(err) })
注:請求后臺接口時要在請求頭上加{responseType: ’blob’};download 設(shè)置文件名時,可以直接設(shè)置擴展名,如果沒有設(shè)置瀏覽器將自動檢測正確的文件擴展名并添加到文件。
3、通過 js-file-download 插件安裝:
npm install js-file-download --S
使用
import fileDownload from ’js-file-download’axios.get(`/operation/ruleImport/template`, {responseType: ’blob’ //返回的數(shù)據(jù)類型 }) .then(res => {fileDownload(res.data, this.fileName) })
以上就是vue中如何下載excel流文件及設(shè)置下載文件名的詳細(xì)內(nèi)容,更多關(guān)于vue中下載excel流文件及設(shè)置下載文件名的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章: