导出文件的公共方法
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', 导出文件是excelheaders: {'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);}});
}