fetch請求數據流並下載為文件


前端獲取流數據並進行下載。

1.后端設置響應類型

1 response.setContentType("application/octet-stream"); // 設置響應類型

2.前端通過fetch獲取流

通過response.blob()獲取bolb

 1 fetch('/xd/editor/total/workload', function (response) {
 2             response.blob().then((blob) => {
 3                 saveBlobAs(blob, 'result.xls')
 4             })
 5         }, function (result) {
 6             console.info("獲取數據失敗" + result.message);
 7         })
 8 
 9 // 保存bolb的方法
10 function saveBlobAs (blob, filename) {
11         if (window.navigator.msSaveOrOpenBlob) {
12             navigator.msSaveBlob(blob, filename)
13         } else {
14             const anchor = document.createElement('a')
15             const body = document.querySelector('body')
16             anchor.href = window.URL.createObjectURL(blob)
17             anchor.download = filename
18 
19             anchor.style.display = 'none'
20             body.appendChild(anchor)
21 
22             anchor.click()
23             body.removeChild(anchor)
24 
25             window.URL.revokeObjectURL(anchor.href)
26         }
27     }

 


免責聲明!

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



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