欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

axios請(qǐng)求設(shè)置responseType為'blob'或'arraybuffer'下載時(shí)如何正確處理返回值

 更新時(shí)間:2023年01月12日 09:31:07   作者:代碼修整工  
這篇文章主要給大家介紹了關(guān)于axios請(qǐng)求設(shè)置responseType為'blob'或'arraybuffer'下載時(shí)如何正確處理返回值的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

問(wèn)題:

調(diào)用后臺(tái)圖片接口,后臺(tái)返回二進(jìn)制流圖片數(shù)據(jù)格式。前端接收到流后處理數(shù)據(jù)顯示在img標(biāo)簽。

解決:

1、設(shè)置axios接收參數(shù)格式為"arraybuffer":

responseType: 'arraybuffer'

2、轉(zhuǎn)換為base64格式圖片數(shù)據(jù)在img標(biāo)簽顯示:

return 'data:image/png;base64,' + btoa(
    new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
  );

返回的string直接放在img標(biāo)簽src可直接顯示

設(shè)置axios接收參數(shù)格式為"blob":

axios.post( ExportUrl, Params, {
    responseType: 'blob'
  })
  .then(function(response) {
    this.url = window.URL.createObjectURL(new Blob([response.data]));
    
  });

通過(guò)a標(biāo)簽下載文件

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();

responseType值的類(lèi)型

數(shù)據(jù)類(lèi)型
‘’DOMString(默認(rèn)類(lèi)型)
arraybufferArrayBuffer對(duì)象
blobBlob對(duì)象
documentDocumnet對(duì)象
jsonJavaScript object, parsed from a JSON string returned by the server
textDOMString

實(shí)例

返回值不同情況的處理方式,舉例如下:

①、請(qǐng)求設(shè)置為 responseType: ‘arraybuffer’,

請(qǐng)求成功時(shí),后端返回文件流,正常導(dǎo)出文件;

請(qǐng)求失敗時(shí),后端返回json對(duì)象,如:{“Status”:“false”,“StatusCode”:“500”,“Result”:“操作失敗”},也被轉(zhuǎn)成了arraybuffer

此時(shí)請(qǐng)求成功和失敗返回的http狀態(tài)碼都是200

解決方案:將已轉(zhuǎn)為arraybuffer類(lèi)型的數(shù)據(jù)轉(zhuǎn)回Json對(duì)象,然后進(jìn)行判斷

代碼如下

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)))不報(bào)錯(cuò),說(shuō)明后臺(tái)返回的是json對(duì)象,則彈框提示
        //如果JSON.parse(enc.decode(new Uint8Array(res.data)))報(bào)錯(cuò),說(shuō)明返回的是文件流,進(jìn)入catch,下載文件
        let enc = new TextDecoder('utf-8')
        res = JSON.parse(enc.decode(new Uint8Array(res.data))) //轉(zhuǎn)化成json對(duì)象
        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();
      }
    }

②、請(qǐng)求設(shè)置為 responseType: ‘blob’,

解決方案:將已轉(zhuǎn)為blob類(lèi)型的數(shù)據(jù)轉(zhuǎn)回Json對(duì)象,然后進(jìn)行判斷

代碼如下

 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)不報(bào)錯(cuò),說(shuō)明this.result是json對(duì)象,則彈框提示
          // 如果JSON.parse(this.result)報(bào)錯(cuò),說(shuō)明返回的是文件流,進(jìn)入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
    }

總結(jié)

到此這篇關(guān)于axios請(qǐng)求設(shè)置responseType為'blob'或'arraybuffer'下載時(shí)如何正確處理返回值的文章就介紹到這了,更多相關(guān)axios請(qǐng)求設(shè)置responseType下載返回值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論