download通用下载方法自定义

126 阅读1分钟

优化若依通用下载方法,随手记录下

export function download(url, params, filename, config) {
  let infoMsg = this.$notify.info({
    title: "消息",
    dangerouslyUseHTMLString: true,
    message: '<strong>正在下载文件,勿退出,请稍后 <i class="el-icon-loading"></i></strong>',
    duration: 0,
    showClose: false
  });
  return service.post(url, params, {
    transformRequest: [(params) => {
      return tansParams(params)
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
      infoMsg.close(); //提示框关闭
      this.$notify({
        title: "成功",
        message: "下载完成",
        type: "success",
      });

    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      infoMsg.close(); //提示框关闭
      this.$notify({
        title: "失败",
        message: errMsg,
        type: "error",
      });

    }
  }).catch((r) => {
    console.error(r)
    infoMsg.close(); //提示框关闭
    this.$notify({
      title: "失败",
      message: errMsg,
      type: "下载文件出现错误,请联系管理员",
    });
    // Message.error('下载文件出现错误,请联系管理员!')
    // downloadLoadingInstance.close();
  })
}