js axios文件流下載

downTemplate: function(id) {
      // partyAccountRole.vue頁面
      this.$message.info("正在下載,請稍等");
      let params = {
        id: id
      };
      // let param ={"templeType":this.updateParams.templeType}
      //這種是通過location.href直接下載
      //location.href = this.$fetch.getBaseUrl() + "/system/" +"/roleDa/importTemplateFile/"+this.updateParams.templeType;
      //這下面則是通過創建a標籤鏈接加click方法下載
      this.$fetch
        .downloadReportAudit(params, { responseType: "arraybuffer" })
        .then(
          resp => {
            console.log(resp.data);
            if (resp.status == "200") {
              try {
                if (resp.data.byteLength > 0) {
                  let type = resp.headers["content-type"];
                  let url = window.URL.createObjectURL(
                    new Blob([resp.data], { type: type })
                  );
                  let link = document.createElement("a");
                  link.style.display = "none";
                  link.href = url;
                  link.setAttribute(
                    "download",
                    decodeURI(resp.headers["file-name"])
                  );
                  document.body.appendChild(link);
                  link.click();
                } else {
                  this.$message.error("下載報告失敗,文件不存在!");
                }
              } catch (e) {
                this.$message.error("下載報告失敗!");
              }
            } else {
              this.$message.error("下載報告失敗!");
            }
          },
          error => {
            this.$message.error(error.message);
          }
        );
    },

下面這裏有多了個響應類型判斷,有的話就認爲是流下載。沒有的話,就參數少個responseType 方法體其他內容都一樣。

//post請求
function doPost(url, params, isLoading, responseType) {
  console.log(sessionStorage.getItem("authorization"));
  console.log("axios.defaults.headers.authorization", axios.defaults.headers.authorization);
  if (axios.defaults.headers.authorization == null) {
    axios.defaults.headers.authorization = sessionStorage.getItem("authorization");
  }
  return new Promise(function (resolve, reject) {
    let loadingInstance1;
    if (isLoading)
      loadingInstance1 = Loading.service({
        fullscreen: false,
        target: ".loading"
      });
    if (responseType != null) {
      postActionWithResType(url, params, isLoading, resolve, reject, loadingInstance1, responseType);
    } else {
      postAction(url, params, isLoading, resolve, reject, loadingInstance1);
    }
  })
}

實際封裝的請求操作

function postActionWithResType(url, params, isLoading, resolve, reject, loadingInstance1, responseType) {
  axios.post(url, params, responseType).then((response) => {
    if (isLoading)
      loadingInstance1.close();

    if (response.data.returnCode && response.data.returnCode != '0') {
      if (response.data.returnMsg.toLowerCase().indexOf("exception") == -1) {
        Message({
          message: response.data.returnMsg,
          //   message: '系統異常,請聯繫管理員',
          type: 'error',
          //大於40則據長度停留,否則默認3秒
          duration: response.data.returnMsg.length > 40 ? (response.data.returnMsg.length / 8) * 1000 : 3000
        })
      } else {
        MessageBox({
          title: "出錯",
          //message: response.data.returnMsg
          message: '系統異常,請聯繫管理員'
        })
      }
      //由於可能失敗還有邏輯需要執行所以沒有攔截
      // return false;
    }
    if (response.data.returnCode && response.data.returnCode == '901') {
      sessionStorage.setItem("menus", "");
      sessionStorage.setItem("userName", "");
      sessionStorage.setItem("depart", "");
      sessionStorage.setItem("userId", "");
      sessionStorage.setItem("ruleCodes", "");
      sessionStorage.setItem("authorization", "");
      router.push({
        path: '/login'
      });
      return false;
    }

    resolve(response);
  }).catch((error) => {
    if (isLoading)
      loadingInstance1.close();
    reject(error);
  })
}

下載的響應內容類型:這裏是下載xlsx文件,這個是根據後端返回的定義類型。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章