axios 設置 responseType:Blob,后台返回的數據會被強制轉為blob類型,這時后台返回的數據會有兩種情況要處理:
1. 數據異常,后台返回 blob 類型異常信息:
使用 new FileReader(),將 blob 轉為 json,然后進行處理
2. 數據正常,后台返回 blob 文件流:
通過方法,直接下載
廢話不多說,直接上代碼👇👇👇
1 let that = this 2 axios.get({ 3 url: 'xxxxxx', 4 method: 'get', 5 data:{}, 6 responseType: 'blob', // 后台返回的數據會被強制轉為blob類型 7 }).then(res => { 8 let reader = new FileReader(); 9 reader.readAsText(res) 10 reader.onload = function (result) { 11 try { 12 let resData = JSON.parse(result.target.result); // 解析對象成功,說明是json數據 13 if (resData.code) { 14 that.$message({ 15 type: 'error', 16 message: resData.desc 17 }) 18 } 19 } catch (err) { // 解析成對象失敗,說明是正常的文件流 20 let blob = new Blob([res], {type: "application/vnd.ms-excel"}); 21 var link = document.createElement('a'); 22 link.href = window.URL.createObjectURL(blob); 23 link.download = `文件名.xls`; 24 link.click() 25 } 26 }; 27 })
謝謝支持,Thank you so much!