ant design 中,使用dva/fetch 設置導致無法從后台導出excel的問題


最近使用antd 做一個后台管理系統中,業務場景下需要將數據導出為excel,后端使用POI,結果數據怎么都無法生成,后面發現原來是前端限制了header 中可以接受的數據類型為json,無法接受blob的類型,后來改用了axios,就可以順利導出了,下面是導出的代碼

 

 1 import axios from 'axios';
 2 
 3 async function getExcel(url, fileName) {
 4   const token = localStorage.getItem('token');
 5   axios
 6     .get(url, {
 7       responseType: 'blob', // 表明返回服務器返回的數據類型,
 8       headers: {
 9         Authorization: 'Bearer ' + token,
10         Accept: 'application/json',
11       },
12     })
13     .then(res => {
14       const content = res;
15       const blob = new Blob([content.data], {
16         type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
17       });
18       // return;
19       if ('download' in document.createElement('a')) {
20         // 非IE下載
21         const elink = document.createElement('a');
22         elink.download = fileName;
23         elink.style.display = 'none';
24         elink.target = '_blank';
25         elink.href = URL.createObjectURL(blob);
26         document.body.appendChild(elink);
27         console.log(elink);
28         elink.click();
29         URL.revokeObjectURL(elink.href); // 釋放URL 對象
30         document.body.removeChild(elink);
31         // window.location.reload();
32       } else {
33         // IE10+下載
34         navigator.msSaveBlob(blob, fileName);
35         window.location.reload();
36       }
37     });
38 }
39 export default {
40   getExcel,
41 };


 

有不懂得可以加我的qq,773935581,歡迎大家一起學習交流


免責聲明!

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



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