fetch请求数据流并下载

前端获取流数据并进行下载。

1.后端设置响应类型

1 response.setContentType("application/octet-stream"); // 设置响应类型

2.前端通过fetch获取流

通过response.blob()获取bolb

 1 app.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     }

猜你喜欢

转载自www.cnblogs.com/jyughynj/p/12625983.html