vue中下載excel流文件及設置下載文件名


接上篇,有導入也就有導出需求。

導出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`)

這兩種使用方法的不同:

    • window.location:當前頁跳轉,也就是重新定位當前頁;只能在網站中打開本網站的網頁。

    • window.open:在新窗口中打開鏈接;可以在網站上打開另外一個網站的地址。

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 = 'none'
            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`, {
            responseType: 'blob' //返回的數據類型
        })
        .then(res => {
            fileDownload(res.data, this.fileName)
        })

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM