Stories

Detail Return Return

二進制文件下載實例,blob、ArrayBuffer區別 - Stories Detail

背景

下載文件功能,點擊下載按鈕,後端返回二進制文件流,前端執行下載文件功能;當返回錯誤信息時前端能夠正確提示。

步驟一:請求設置responseType

請求數據時responseType不同,ArrayBuffer為arraybuffer,blob為blob。
image.png

步驟二:對響應進行攔截並判斷

  • 正確情況
    創建a標籤並下載。

    const blob = new Blob([res]);
    const fileName = row.fileName;  //文件名稱,帶後綴
    const link = document.createElement('a');
    link.href = URL.createObjectURL(res);
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
  • 錯誤情況
    當下載失敗時,轉換返回值,並進行提示。
    image.png

關於blob、ArrayBuffer區別詳見下面鏈接:
https://blog.csdn.net/qq_38974163/article/details/119862253

Add a new Comments

Some HTML is okay.