从后端获取文件数据并导出

导出文件的公共方法

export const download = (res, tools) => {
  const { message, hide } = tools;
  const fileReader: any = new FileReader();
  console.log('fileReader-res>>>', res);
  fileReader.onload = (e) => {
    if (res?.data?.type === 'application/json') {
      try {
        const jsonData = JSON.parse(fileReader.result);
        if (jsonData?.success === false && jsonData?.message) {
          hide?.();
          message.error(jsonData?.message);
        }
      } catch (error) {
        hide?.();
        message.error(getLocalTextFun('common.export.error'));
      }
    } else {
      try {
        const filename = (
          res.response.headers.get('content-disposition').split('filename=')?.[1] || ''
        ).replace(/"/g, '');
        if ('msSaveOrOpenBlob' in navigator) {
          window.navigator.msSaveOrOpenBlob(res.data, decodeURI(filename));
        } else {
          const blob = new Blob([res.data]);
          const url = window.URL.createObjectURL(blob);
          const link: any = document.createElement('a');
          link.href = url;
          link.download = decodeURI(filename);
          link.click();
          hide?.();
          window.URL.revokeObjectURL(url);
        }
      } catch (err: any) {
        hide?.();
        message.error(getLocalTextFun('common.export.error'));
      }
    }
  };
  try {
    fileReader.readAsText(res.data);
  } catch (e) {
    hide?.();
    message.error(getLocalTextFun('common.export.error'));
  }
};

请求后端接口

const hide = message.loading(`加载中...`, 0);
const res = await exportI18nByLocal(record.locale);
download(res, {message, hide});

接口请求

export async function executeAndTryCatch(func: any) {
  try {
    return await func();
  } catch (error: any) {
    return error;
  }
}
export function exportI18nByLocal(locale:string) {
  return executeAndTryCatch(() =>
    request<Record<string, any>>(`${api().i18nExport}?locale=${locale}`, {
      method: 'GET',
      responseType: 'blob',
      //'Accept': 'application/vnd.ms-excel', 导出文件是excel
      headers: {
        'Accept': 'application/vnd.ms-excel',
        "locale": locale
      },
      //  获取返回数据结构里面包含response数据 如下图
      getResponse: true,
    }).then((res: any) => judgeErrorByResponseType(res)),
  );
}

接口返回结果
在这里插入图片描述

判断文件是否导出失败

function judgeErrorByResponseType(response: any) {
  const res = response.response;
  return new Promise((resolve, reject) => {
    if (!res) resolve('');
    if (res.headers.get('Content-Type').includes('json')) {
      const reader = new FileReader();
      reader.onload = () => {
        const { result }: any = reader;
        const errorInfos = JSON.parse(result);
        resolve(errorInfos);
      };
      reader.onerror = (err) => {
        reject(err);
      };
      reader.readAsText(response.data);
    } else {
      resolve(response);
    }
  });
}
上一篇:解密Oracle数据库引擎:揭开数据存储的神秘面纱(二)


下一篇:【Review+预测】测试架构演进的曲折之路