axios請求設置responseType為'blob'或'arraybuffer'下載時,正確處理返回值


問題:調用后台圖片接口,后台返回二進制流圖片數據格式。前端接收到流后處理數據顯示在img標簽。
解決:
1、先設置axios接收參數格式為"arraybuffer":
responseType: 'arraybuffer'
 
2、轉換為base64格式圖片數據在img標簽顯示:
return 'data:image/png;base64,' + btoa(
    new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
  );
返回的string直接放在img標簽src可直接顯示
 
3、先設置axios接收參數格式為"blob":
axios.post( ExportUrl, Params, {
    responseType: 'blob'
  })
  .then(function(response) {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    console.log(url)
  });
 
 
通過a標簽下載文件
const url = '下載的url鏈接';
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
link.setAttribute('download', 'Excel名字.xlsx');
document.body.appendChild(link);
link.click();
 
 
 
前言
使用axios請求api下載導出一個文件時,接口返回值可能會出現兩種情況:
1、文件流
2、json對象
 
 
responseType值的類型
值 
數據類型
''
 DOMString(默認類型)
arraybuffer
ArrayBuffer對象
blob
Blob對象
document 
Documnet對象
json
JavaScript object, parsed from a JSON string returned by the server
text
DOMString
 
實例
返回值不同情況的處理方式,舉例如下:
 
①、請求設置為 responseType: 'arraybuffer',
請求成功時,后端返回文件流,正常導出文件;
請求失敗時,后端返回json對象,如:{"Status":"false","StatusCode":"500","Result":"操作失敗"},也被轉成了arraybuffer
 
此時請求成功和失敗返回的http狀態碼都是200
 
解決方案:將已轉為arraybuffer類型的數據轉回Json對象,然后進行判斷
 
代碼如下
async downloadFile (file) {
      let res = await this.$axios.post(this.API.order.tradeImpExcle, { responseType: "arraybuffer" });
      if (!res) return;
      try {
        //如果JSON.parse(enc.decode(new Uint8Array(res.data)))不報錯,說明后台返回的是json對象,則彈框提示
        //如果JSON.parse(enc.decode(new Uint8Array(res.data)))報錯,說明返回的是文件流,進入catch,下載文件
        let enc = new TextDecoder('utf-8')
        res = JSON.parse(enc.decode(new Uint8Array(res.data))) //轉化成json對象
        if (res.Status == "true") {
          this.refresh()
          this.$message.success(res.Msg)
        } else {
          this.$message.error(res.Result)
        }
      } catch (err) {
        const content = res.data;
        const blob = new Blob([content]);
        let url = window.URL.createObjectURL(blob);
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute(
          "download",
          res.headers["content-disposition"].split("=")[1]
        );
        document.body.appendChild(link);
        link.click();
      }
    }
 
②、請求設置為 responseType: 'blob',
 
解決方案:將已轉為blob類型的數據轉回Json對象,然后進行判斷
 
代碼如下
 async downloadFile (file) {
      let formData = new FormData();
      formData.append("allTradesExcelFile", file);
      let res = await this.$axios.post(this.API.order.tradeImpExcle, formData, { responseType: "blob" });
      if (!res) return;
      let r = new FileReader()
      let _this = this
      r.onload = function () {
        try {
          // 如果JSON.parse(this.result)不報錯,說明this.result是json對象,則彈框提示
          // 如果JSON.parse(this.result)報錯,說明返回的是文件流,進入catch,下載文件
          res = JSON.parse(this.result)
          if (res.Status == "true") {
            _this.refresh()
            _this.$message.success(res.Msg)
          } else {
            _this.$message.error(res.Result)
          }
        } catch (err) {
          const content = res.data;
          const blob = new Blob([content]);
          let url = window.URL.createObjectURL(blob);
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute(
            "download",
            res.headers["content-disposition"].split("=")[1]
          );
          document.body.appendChild(link);
          link.click();
        }
      }
      r.readAsText(res.data) // FileReader的API
    }

 

 


免責聲明!

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



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