vue+axios實現文件下載——請求的responseType為blob


vue+axios實現文件下載

 

功能:點擊導出按鈕,提交請求,下載excel文件;

 

第一步:跟后端童鞋確認交付的接口的response header設置了

以及返回了文件流。

 

第二步:修改axios請求的responseType為blob,以post請求為例:

復制代碼
axios({
    method: 'post',
    url: 'api/user/',
    data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
    },
    responseType: 'blob'
}).then(response => {
    this.download(response)
}).catch((error) => {

})
復制代碼

 

第三步:請求成功,拿到response后,調用download函數(創建a標簽,設置download屬性,插入到文檔中並click)

復制代碼
methods: {
    // 下載文件
    download (data) {
        if (!data) {
            return
        }
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', 'excel.xlsx')
        
        document.body.appendChild(link)
        link.click()
    }
}
復制代碼

 


免責聲明!

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



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