js 的 http 请求二进制文件流并下载 excel

结论:

  • 请求头 header 中无需单独设置 responseType: “blob”,下文的只是用来作为响应后不同处理方式的参数判断的
  • 后端响应的是以下任何一种都可
    • content-type: application/octet-stream;charset=UTF-8
    • content-type: application/vnd.ms-excel;charset=UTF-8
  • new Blob 需要设置类型为 application/octet-stream;charset=UTF-8
  • 注:以上 charset=UTF-8 是默认值,都可不写,效果是一样的

调用

public exportExcel = async () => {
  const [err, res] = await (httpService as IExportExcel.IExample)(
    "POST",
    "/export/order-sales/excel",
    this.state.searchParam,
    {},
    {
      responseType: "blob",
    }
  );
  if (err || !res) {
    return;
  }
}

请求方法

export const httpService = (
  method: IMethod,
  url: string,
  data: any = {},
  appendHeaders: any = {},
  otherParams?: any
) => {
  const platform = "H5";
  const masterInfoStore = (stores as IStore).MasterInfoTable!.localStore;
  const userInfoStore = (stores as IStore).UserInfoTable!.localStore;
  const Http = service.HttpService;
  const countryCode = userInfoStore.countryCode || "GB";
  const hostMap: IHostMap = host;
  let requestAddress: any = hostMap[countryCode]
    ? `${hostMap[countryCode].SERVER_BASE_API}${url}`
    : "";

  if (otherParams && otherParams.erp) {
    const baseUrl = hostMap[countryCode].SERVER_BASE_API.replace(
      "/api/merchant",
      ""
    );
    requestAddress = baseUrl + url;
  }
  if (otherParams && otherParams.thirdPartyWebsite) {
    requestAddress = url;
  }
  const token =
    getUserProperty() === "master"
      ? masterInfoStore.token || null
      : userInfoStore.token || null;

  const headerMaps = {
    "content-type": "application/json",
    token: token,
    platform,
    lang: languageType[userInfoStore.language || "zh_CN"],
    countryCode: languageType[userInfoStore.countryCode || "CN"],
    ...appendHeaders,
  };

  return new Promise((resolve, reject) => {
    Http(method, requestAddress, data, headerMaps, otherParams)
      .then((response: any) => {
        if (
          otherParams &&
          otherParams.responseType &&
          otherParams.responseType === "blob"
        ) {
          if (response.data.size === 0) {
            toastMessage.error({ content: "该报表无数据" });
            resolve([{ error: true }, null]);
            return;
          }
          let name = "报表";
          if (response.headers["content-disposition"]) {
            const nameURI = response.headers["content-disposition"]
              .split(";")[1]
              .split("=")[1];
            name = decodeURIComponent(nameURI);
          }
          exportExcel(response.data, name);
        }
        if (response) {
          if (otherParams && otherParams.thirdPartyWebsite) {
            resolve([null, response]);
          }
        }
        let { code, data, message } = response as any;
        // 401 权限缺失,跳转至登录页
        if (code === 401) {
          const pathname = new URL(location.href).pathname;
          if (getUserProperty() === "master") {
            // 大客户
            if (pathname !== "/master/login") {
              masterLogoutService();
            }
          } else {
            if (pathname !== "/login") {
              userLogoutService();
            }
          }
        }

        if (code < 999 && code !== 1) {
          echoHttpServiceMessage(message || LanguageService.entry_isTEXT1047());
          console.log("http 请求的返回值 code 不等于 1:", { code, message });

          reject({ code, message });
          return false;
        }
        console.log("http 请求的返回值 response:::", response);
        resolve([code > 999 ? { code, message } : null, data]);
      })
      .catch((err) => {
        console.log("http 请求的返回值的 catch:", err);

        echoHttpServiceMessage(err.toString());
        reject(err);
      });
  });
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值