mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
126 lines
3.4 KiB
TypeScript
126 lines
3.4 KiB
TypeScript
/**
|
|
* 通用文件导出工具
|
|
* 用于下载 Excel、PDF 等二进制文件
|
|
*/
|
|
import { useAppConfig } from '@vben/hooks';
|
|
import { useAccessStore } from '@vben/stores';
|
|
|
|
import { message } from 'ant-design-vue';
|
|
|
|
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
|
|
|
function formatToken(token: null | string) {
|
|
return token ? `Bearer ${token}` : null;
|
|
}
|
|
|
|
/** 从 Content-Disposition 解析文件名(与后端 attachment; filename="..." 对齐) */
|
|
function parseFilenameFromContentDisposition(
|
|
contentDisposition: string | null,
|
|
): string | null {
|
|
if (!contentDisposition) return null;
|
|
const utf8Match = /filename\*=UTF-8''([^;\s]+)/i.exec(contentDisposition);
|
|
if (utf8Match?.[1]) {
|
|
try {
|
|
return decodeURIComponent(utf8Match[1].replace(/"/g, ''));
|
|
} catch {
|
|
return utf8Match[1].replace(/"/g, '');
|
|
}
|
|
}
|
|
const quoted = /filename="([^"]+)"/i.exec(contentDisposition);
|
|
if (quoted?.[1]) return quoted[1];
|
|
const plain = /filename=([^;\s]+)/i.exec(contentDisposition);
|
|
if (plain?.[1]) return plain[1].replace(/^"|"$/g, '');
|
|
return null;
|
|
}
|
|
|
|
async function triggerBlobDownload(
|
|
response: Response,
|
|
fallbackFilename: string,
|
|
) {
|
|
const contentType = response.headers.get('Content-Type') || '';
|
|
const blob = await response.blob();
|
|
|
|
if (blob.size === 0) {
|
|
throw new Error('下载文件为空');
|
|
}
|
|
|
|
if (contentType.includes('application/json')) {
|
|
const text = await blob.text();
|
|
try {
|
|
const json = JSON.parse(text);
|
|
message.error(json.message || '下载失败');
|
|
} catch {
|
|
message.error('下载失败');
|
|
}
|
|
return;
|
|
}
|
|
|
|
const headerName =
|
|
parseFilenameFromContentDisposition(
|
|
response.headers.get('Content-Disposition'),
|
|
) || fallbackFilename;
|
|
|
|
const downloadUrl = window.URL.createObjectURL(blob);
|
|
const link = document.createElement('a');
|
|
link.href = downloadUrl;
|
|
link.download = headerName;
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
document.body.removeChild(link);
|
|
window.URL.revokeObjectURL(downloadUrl);
|
|
}
|
|
|
|
export async function exportByGet(url: string, filename: string) {
|
|
const accessStore = useAccessStore();
|
|
const fullUrl = `${apiURL}${url}`;
|
|
|
|
try {
|
|
const response = await fetch(fullUrl, {
|
|
method: 'GET',
|
|
headers: {
|
|
Authorization: formatToken(accessStore.accessToken) || '',
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
}
|
|
|
|
await triggerBlobDownload(response, filename);
|
|
message.success('下载成功');
|
|
} catch (error) {
|
|
console.error('下载失败:', error);
|
|
message.error('下载失败,请稍后重试');
|
|
}
|
|
}
|
|
|
|
export async function exportByPost(
|
|
url: string,
|
|
params: Record<string, unknown>,
|
|
filename: string,
|
|
) {
|
|
const accessStore = useAccessStore();
|
|
const fullUrl = `${apiURL}${url}`;
|
|
|
|
try {
|
|
const response = await fetch(fullUrl, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Authorization: formatToken(accessStore.accessToken) || '',
|
|
},
|
|
body: JSON.stringify(params),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
}
|
|
|
|
await triggerBlobDownload(response, filename);
|
|
message.success('导出成功');
|
|
} catch (error) {
|
|
console.error('导出失败:', error);
|
|
message.error('导出失败,请稍后重试');
|
|
}
|
|
}
|