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文件,这个是根据后端返回的定义类型。
js axios文件流下载_第1张图片

你可能感兴趣的:(Web前端,另类实用,vue)