mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 11:09:19 +08:00
feat(frontend): 店铺概览页添加导出按钮
- 新增 exportByPost 通用导出工具(处理 blob 下载) - 店铺概览页导出按钮绑定事件,支持当前页面日期范围导出 - shop/apis.ts 新增导出 API 函数
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* 通用文件导出工具
|
||||
* 用于下载 Excel、PDF 等二进制文件
|
||||
*/
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
import { message } from 'ant-design-vue';
|
||||
|
||||
import { useAppConfig } from '@vben/hooks';
|
||||
|
||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
|
||||
function formatToken(token: null | string) {
|
||||
return token ? `Bearer ${token}` : null;
|
||||
}
|
||||
|
||||
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}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('Content-Type') || '';
|
||||
const blob = await response.blob();
|
||||
|
||||
if (blob.size === 0) {
|
||||
throw new Error('下载文件为空');
|
||||
}
|
||||
|
||||
// 如果返回的是 JSON 错误(而非文件),提示错误信息
|
||||
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 downloadUrl = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = downloadUrl;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(downloadUrl);
|
||||
message.success('导出成功');
|
||||
} catch (error) {
|
||||
console.error('导出失败:', error);
|
||||
message.error('导出失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user