處理下載接口返回的文件流數據


 1 /**
 2  * 處理下載接口返回的文件流數據
 3  * @param {*} res http請求返回數據
 4  */
 5 function download(res) {
 6   // 錯誤處理
 7   if (res.data.type == "application/json") {
 8     let reader = new FileReader();
 9     reader.readAsText(res.data, 'utf-8');
10     reader.onload = function () {
11       let json_data = JSON.parse(reader.result);
12       Message({
13         showClose: true,
14         message: json_data.Message,
15         type: "error"
16       });
17     }
18     return;
19   }
20   // 下載處理
21   let filename = "content-disposition" in res.headers ?
22     decodeURIComponent(
23       res.headers["content-disposition"]
24         .split(";")[1]
25         .split("=")[1]
26         .replace(/"/g, "")
27     ) :
28     "下載文件";
29   try {
30     if (window.navigator.msSaveOrOpenBlob) {
31       navigator.msSaveBlob(res.data, filename);
32     } else {
33       let blob = new Blob([res.data], {
34         type: "application/vnd.ms-excel"
35       });
36       let url = URL.createObjectURL(blob);
37       let link = document.createElement("a");
38       link.setAttribute("href", url);
39       link.setAttribute("download", filename);
40       link.style.display = "none";
41       document.body.appendChild(link);
42       link.click();
43       URL.revokeObjectURL(url); // 釋放URL 對象
44       document.body.removeChild(link);
45     }
46   } catch (err) {
47     // console.log(err)
48   }
49 }

 


免責聲明!

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



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