vue項目中實現文件下載功能


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

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

 1 this.$axios({
 2                     method: 'post',
 3                     url: '/api/market/exportEmployee.do',
 4                     // headers里面設置token
 5                     headers: {
 6                       'Content-Type': 'application/json',
 7                       // "token":window.sessionStorage.getItem('token')
 8                     },
 9                     data: {
10                         'department_id': parseInt(window.sessionStorage.getItem("departmentId")),
11                           'startTime': this.date +'-1',
12                           'endTime': this.date +'-31'
13                     },
14                     // 二進制流文件,一定要設置成blob,默認是json
15                     responseType: 'blob'
16                     
17                 }).then(res => {
18                     console.log(res)
19                     if(!res.data){
20                                return
21                            }
22                            var name = this.date + "月" + this.departmentName +"銷售分析統計.xls";
23                            var blob = new Blob([res.data]);
24                            var url = window.URL.createObjectURL(blob);
25                            var aLink = document.createElement("a");
26                            aLink.style.display = "none";
27                            aLink.href = url;
28                            aLink.setAttribute("download", name);
29                            document.body.appendChild(aLink);
30                            aLink.click();
31                            document.body.removeChild(aLink); //下載完成移除元素
32                            window.URL.revokeObjectURL(url); //釋放掉blob對象
33                   })

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


免責聲明!

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



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