前端接受後端檔案流並下載的幾種方法
前言
專案中經常會遇到需要匯出列表內容,或者下載檔案之類的需求。結合各種情況,我總結了前端最常用的三種方法來接受後端傳過來的檔案流並下載,針對不同的情況可以使用不同的方法。
方法一
使用場景
針對後端的 get
請求
具體實現
<a href="後端檔案下載介面地址" >下載檔案</a> 複製程式碼
直接用個 <a>
標籤來接受後端的檔案流
方法二
使用場景
針對後端的 post
請求 利用原生的 API%2FXMLHttpRequest" rel="nofollow,noindex"> XMLHttpRequest
方法實現
具體實現
function request () { const req = new XMLHttpRequest(); req.open('POST', '<介面地址>', true); req.responseType = 'blob'; req.setRequestHeader('Content-Type', 'application/json'); req.onload = function() { const data = req.response; const a = document.createElement('a'); const blob = new Blob([data]); const blobUrl = window.URL.createObjectURL(blob); download(blobUrl) ; }; req.send('<請求引數:json字串>'); }; function download(blobUrl) { const a = document.createElement('a'); a.style.display = 'none'; a.download = '<檔名>'; a.href = blobUrl; a.click(); document.body.removeChild(a); } request(); 複製程式碼
方法三
使用場景
針對後端的 post
請求 利用原生的 fetch
方法實現
具體實現
function request() { fetch('<介面地址>', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: '<請求引數:json字串>', }) .then(res => res.blob()) .then(data => { let blobUrl = window.URL.createObjectURL(data); download(blobUrl); }); } function download(blobUrl) { const a = document.createElement('a'); a.style.display = 'none'; a.download = '<檔名>'; a.href = blobUrl; a.click(); document.body.removeChild(a); } request(); 複製程式碼
總結
get post