前端如何根據后端返回文件流下載


前端實現下載excel、img、zip....方法有兩種

    1. 直接調接口進行下載 后端進行處理                        多GET請求

    2. 調取接口返回對應的文件流,前端進行處理           多POST請求

(1) zip下載:(未對IE瀏覽器做處理)

 1         let dataStr = `taskId=${this.taskVal}&versionNo=${this.versionVal}&flag=${this.flagVal}`;
 2         axios.get("/dq/task/record/detail/excel/exportDetail2?" + dataStr, {
 3           responseType: 'blob'  // zip文件流需要添加,不然文件無法打開
 4         }).then(res => {
 5            let Res = new ResDatas({
 6             res,
 7           }).init();
 8           let contentType = res.headers['content-type'];
 9           let contentDisposition = res.headers['content-disposition'];
10           if(contentType.indexOf('application/json') != -1) {
11             this.$message({
12               message: Res,
13               type: "warning"
14             });
15           } else {
16             contentDisposition = contentDisposition.split(";")[1];
17             let filename = contentDisposition.split("=")[1];
18             let filenameStr = window.decodeURI(filename.split(",")[0],"utf-8"); // 下載的文件名稱
19             _customDownLoadZipGet(res.data, filenameStr);
20           }
21         })
 1 /**
 2  * @name: 
 3  * @param {type} 
 4  * @return: 
 5  * @description: (前端)文件流轉換
 6  */
 7  export const _customDownLoadZipGet = (data, fileName) => {
 8   const blob = new Blob([data]);
 9   const downloadElement = document.createElement("a");
10   const href = window.URL.createObjectURL(blob);
11   //后台再header中傳文件名
12   downloadElement.href = href;
13   downloadElement.download = fileName;
14   document.body.appendChild(downloadElement);
15   downloadElement.click();
16   document.body.removeChild(downloadElement); // 下載完成移除元素
17   window.URL.revokeObjectURL(href); // 釋放掉blob對象
18 };

Blod轉  =>  JSON

1             let reader = new FileReader(); // 創建讀取文件對象
2             reader.addEventListener("loadend", () => {
3               let Res = JSON.parse(reader.result); // 返回的數據
4               this.$message({
5                 message: Res.data,
6                 type: Res.code == "200" ? "success" : "warning"
7               });
8             });
9             reader.readAsText(res.data, 'utf-8'); // 設置讀取的數據以及返回的數據類型為utf-8


免責聲明!

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



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