封装导出工具类

This commit is contained in:
linxd
2025-07-01 09:25:22 +08:00
parent 6c5c5528cb
commit 4e4b9a730d
5 changed files with 57 additions and 113 deletions

View File

@ -1,58 +1,57 @@
/**
* 通用文件下载工具(基于 umi-request + file-saver
*/
import { extend } from 'umi-request';
import { saveAs } from 'file-saver';
// 单独配置一个不拦截响应的 request 实例
const downloadRequest = extend({
timeout: 10000,
responseType: 'blob', // 关键
credentials: 'include', // 根据实际需要携带 cookie
prefix: REQUEST_BASE,
});
/**
* 下载文件通用函数
* @param url 请求地址
* @param params 请求参数(可选)
* @param filename 下载后的文件名(可选)
* @param method 请求方法(默认 POST
* 更稳妥的文件下载方法(绕过 umi-request避免被 JSON 解析)
*/
export async function downloadFile({
url,
params,
filename,
method = 'POST',
}: {
url: string;
params?: Record<string, any>;
filename?: string;
method?: 'GET' | 'POST';
}) {
export async function downloadFile(
url: string,
method: 'GET' | 'POST' = 'POST',
params?: Record<string, any>
) {
try {
const blob: Blob = await downloadRequest(url, {
method,
data: method === 'POST' ? params : undefined,
params: method === 'GET' ? params : undefined,
});
// 尝试从响应头中获取文件名
const contentDisposition = (blob as any).response?.headers?.get?.('content-disposition');
let finalFilename = filename;
if (!finalFilename && contentDisposition) {
const match = contentDisposition.match(/filename="?([^"]+)"?/);
if (match && match[1]) {
finalFilename = decodeURIComponent(match[1]);
}
const cleanedParams: Record<string, any> = {};
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
cleanedParams[key] = value;
}
});
}
finalFilename = finalFilename || '下载文件';
const fetchUrl =
method === 'GET' && params
? `${REQUEST_BASE}${url}?${new URLSearchParams(cleanedParams as any).toString()}`
: `${REQUEST_BASE}${url}`;
saveAs(blob, finalFilename);
} catch (error) {
console.error('文件下载失败:', error);
const response = await fetch(fetchUrl, {
method,
headers: {
'Content-Type': 'application/json',
},
body: method === 'POST' ? JSON.stringify(params) : undefined,
credentials: 'include',
});
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('text/html')) {
const htmlText = await response.text();
console.error('服务器返回 HTML 页面,可能是未登录或接口错误:', htmlText.slice(0, 300));
return;
}
if (!response.ok) {
const text = await response.text();
console.error(`请求失败(${response.status}`, text);
return;
}
const disposition = response.headers.get('content-disposition') || '';
const match = disposition.match(/filename="?([^"]+)"?/);
const fileName = match ? decodeURIComponent(match[1]) : '下载文件.xlsx';
const blob = await response.blob();
saveAs(blob, fileName);
} catch (err) {
console.error('下载失败:', err);
}
}