前端接受後端檔案下載的幾種方法
阿新 • • 發佈:2018-12-17
前言
專案中經常會遇到需要匯出列表內容,或者下載檔案之類的需求。結合各種情況,我總結了前端最常用的三種方法來接受後端傳過來的檔案流並下載,針對不同的情況可以使用不同的方法。
方法一
使用場景
針對後端的get
請求
具體實現
<a href="後端檔案下載介面地址" >下載檔案</a>
複製程式碼
直接用個<a>
標籤來接受後端的檔案流
方法二
使用場景
針對後端的post
請求 利用原生的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
型別,就必須要用方法二或者方法三了。
方法二和方法三怎麼取捨?
- 當你的專案裡的介面請求全是基於
XMLHttpRequest
實現的,這時方法二就更加適合,只要基於你原來專案中的介面請求工具類加以擴充套件就行了。 - 當你的專案裡的介面請求全是基於
fetch
實現的,這時方法三就更加適合,比如我現在的做的一個專案就是基於ant design pro
的後臺管理系統,它裡面的請求類就是基於fetch
request.js
檔案中稍作修改就行。 - 我這裡討論的是兩種原生的請求方式,如果你專案中引用了第三方請求包來發送請求,比如axios之類的,那就要另當別論了。