mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 22:29:19 +08:00
refactor: 统一文件存储与上传流程,解耦 OSS 客户端、存储类型与前端上传模式
This commit is contained in:
@@ -34,16 +34,3 @@ export async function updateCompanyApi(id: number, data: CompanyDTO.UpdateCompan
|
||||
export async function deleteCompanyApi(id: number) {
|
||||
return requestClient.delete<void>(`/company/delete/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传公司Logo
|
||||
*/
|
||||
export async function uploadCompanyLogoApi(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
return requestClient.post<CompanyVO.CompanyInfoVO>('/company/upload-logo', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ export namespace CompanyVO {
|
||||
email?: string;
|
||||
/** logo */
|
||||
logo?: string;
|
||||
/** logo 图片 ID */
|
||||
logoImageId?: number;
|
||||
/** 状态 (0-禁用 1-正常) */
|
||||
status: number;
|
||||
/** 订阅到期时间 */
|
||||
|
||||
@@ -44,19 +44,6 @@ export async function getShopDetailApi(id: number) {
|
||||
return requestClient.get<ShopVO.Info>(`/ec/shop/detail/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传店铺Logo
|
||||
*/
|
||||
export async function uploadShopLogoApi(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
return requestClient.post<ShopVO.Info>('/ec/shop/upload-logo', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页获取店铺商品信息
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* 系统配置 API(需登录)
|
||||
*/
|
||||
import type { SysConfigVO } from './types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/** 获取系统配置(文件存储/上传模式等) */
|
||||
export async function getSysConfigApi() {
|
||||
return requestClient.get<SysConfigVO.Config>('/sys/config');
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './apis';
|
||||
export * from './types';
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 系统配置 VO
|
||||
*/
|
||||
export namespace SysConfigVO {
|
||||
export interface Config {
|
||||
file: FileConfig;
|
||||
}
|
||||
|
||||
export interface FileConfig {
|
||||
/** 存储方式:local / oss */
|
||||
storageType: 'local' | 'oss' | string;
|
||||
/** 上传方式:multipart(传后端)/ direct(直传对象存储) */
|
||||
uploadMode: 'multipart' | 'direct' | string;
|
||||
/** 单文件大小上限(MB) */
|
||||
maxFileSizeMb: number;
|
||||
}
|
||||
}
|
||||
@@ -9,14 +9,18 @@ import { requestClient } from '#/api/request';
|
||||
*/
|
||||
|
||||
/**
|
||||
* 批量上传文件
|
||||
* 批量上传文件(multipart,由后端按 storageType 落盘)
|
||||
* @param files 文件列表
|
||||
* @param category 可选分类
|
||||
*/
|
||||
export async function batchUploadFilesApi(files: File[]) {
|
||||
export async function batchUploadFilesApi(files: File[], category?: string) {
|
||||
const formData = new FormData();
|
||||
files.forEach((file) => {
|
||||
formData.append('files', file);
|
||||
});
|
||||
if (category) {
|
||||
formData.append('category', category);
|
||||
}
|
||||
return requestClient.post<FileVO.Upload[]>(
|
||||
'/sys/file/batch-upload',
|
||||
formData,
|
||||
|
||||
@@ -35,19 +35,6 @@ export async function changePasswordApi(data: UserDTO.ChangePasswordDTO) {
|
||||
return requestClient.post<void>('/user/change-password', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传用户头像
|
||||
*/
|
||||
export async function uploadAvatarApi(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
return requestClient.post<UserVO.UserInfoVO>('/user/upload-avatar', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户菜单
|
||||
*/
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImportTaskVO } from '#/api/ec/import/task';
|
||||
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
@@ -89,9 +89,6 @@ function formatTime(time: string): string {
|
||||
return new Date(time).toLocaleString();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
importTaskStore.init();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -65,8 +65,11 @@ const showDot = computed(() =>
|
||||
notifications.value.some((item) => !item.isRead),
|
||||
);
|
||||
|
||||
// 登录布局挂载:先建用户级 SSE,再拉导入任务
|
||||
// 登录布局挂载:已登录才建 SSE 与导入任务(welcome 等 ignoreAccess 页未登录也会进此布局)
|
||||
onMounted(() => {
|
||||
if (!accessStore.accessToken) {
|
||||
return;
|
||||
}
|
||||
realtimeStore.start();
|
||||
importTaskStore.init();
|
||||
});
|
||||
|
||||
@@ -95,6 +95,14 @@ function setupAccessGuard(router: Router) {
|
||||
const userInfo = userStore.userInfo || (await authStore.fetchUserInfo());
|
||||
const userRoles = userInfo.roles ?? [];
|
||||
|
||||
// 系统配置(刷新页面后补拉)
|
||||
try {
|
||||
const { useAppConfigStore } = await import('#/store/app-config');
|
||||
await useAppConfigStore().ensureLoaded();
|
||||
} catch (error) {
|
||||
console.warn('获取系统配置失败:', error);
|
||||
}
|
||||
|
||||
// 生成菜单和路由
|
||||
const { accessibleMenus, accessibleRoutes } = await generateAccess({
|
||||
roles: userRoles,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { SysConfigVO } from '#/api/sys/config';
|
||||
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { getSysConfigApi } from '#/api/sys/config';
|
||||
|
||||
/**
|
||||
* 系统配置(登录后拉取;含文件上传模式等)。
|
||||
*/
|
||||
export const useAppConfigStore = defineStore('app-config', () => {
|
||||
const config = ref<null | SysConfigVO.Config>(null);
|
||||
const loaded = ref(false);
|
||||
const loading = ref(false);
|
||||
|
||||
const file = computed(() => config.value?.file ?? null);
|
||||
const uploadMode = computed(() => file.value?.uploadMode ?? 'multipart');
|
||||
const storageType = computed(() => file.value?.storageType ?? 'local');
|
||||
const maxFileSizeMb = computed(() => file.value?.maxFileSizeMb ?? 50);
|
||||
const isDirectUpload = computed(() => uploadMode.value === 'direct');
|
||||
|
||||
async function fetchConfig(force = false) {
|
||||
if (loaded.value && !force) {
|
||||
return config.value;
|
||||
}
|
||||
if (loading.value) {
|
||||
return config.value;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
config.value = await getSysConfigApi();
|
||||
loaded.value = true;
|
||||
return config.value;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 确保已加载;未加载则请求 */
|
||||
async function ensureLoaded() {
|
||||
if (!loaded.value) {
|
||||
await fetchConfig();
|
||||
}
|
||||
return config.value;
|
||||
}
|
||||
|
||||
function $reset() {
|
||||
config.value = null;
|
||||
loaded.value = false;
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
return {
|
||||
config,
|
||||
loaded,
|
||||
loading,
|
||||
file,
|
||||
uploadMode,
|
||||
storageType,
|
||||
maxFileSizeMb,
|
||||
isDirectUpload,
|
||||
fetchConfig,
|
||||
ensureLoaded,
|
||||
$reset,
|
||||
};
|
||||
});
|
||||
@@ -19,10 +19,12 @@ import {
|
||||
registerApi,
|
||||
} from '#/api';
|
||||
import { $t } from '#/locales';
|
||||
import { useAppConfigStore } from '#/store/app-config';
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const accessStore = useAccessStore();
|
||||
const userStore = useUserStore();
|
||||
const appConfigStore = useAppConfigStore();
|
||||
const router = useRouter();
|
||||
|
||||
const loginLoading = ref(false);
|
||||
@@ -64,6 +66,13 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
// 获取用户信息
|
||||
userInfo = await fetchUserInfo();
|
||||
|
||||
// 系统配置(上传模式等)
|
||||
try {
|
||||
await appConfigStore.fetchConfig(true);
|
||||
} catch (error) {
|
||||
console.warn('获取系统配置失败:', error);
|
||||
}
|
||||
|
||||
// 获取用户权限码(可选,如果接口不存在则跳过)
|
||||
try {
|
||||
const accessCodes = await getAccessCodesApi();
|
||||
@@ -138,6 +147,13 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
// 获取用户信息
|
||||
userInfo = await fetchUserInfo();
|
||||
|
||||
// 系统配置(上传模式等)
|
||||
try {
|
||||
await appConfigStore.fetchConfig(true);
|
||||
} catch (error) {
|
||||
console.warn('获取系统配置失败:', error);
|
||||
}
|
||||
|
||||
// 获取用户权限码(可选,如果接口不存在则跳过)
|
||||
try {
|
||||
const accessCodes = await getAccessCodesApi();
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { PageQueryDTO } from '#/types/common';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
import { getImportTaskPageApi } from '#/api/ec/import/task';
|
||||
@@ -114,7 +115,11 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
||||
unsubAllDone = null;
|
||||
}
|
||||
|
||||
/** 登录后才拉任务列表并订阅 SSE */
|
||||
async function init() {
|
||||
if (!useAccessStore().accessToken) {
|
||||
return;
|
||||
}
|
||||
subscribeRealtime();
|
||||
await fetchTasks(true);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from './auth';
|
||||
export * from './app-config';
|
||||
export * from './col-sidebar-layout';
|
||||
export * from './import-task';
|
||||
export * from './realtime';
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
/**
|
||||
* 统一文件上传工具
|
||||
* 通过统一文件系统(batchSignUrl)直传 OSS,文件记录自动入库
|
||||
*/
|
||||
import { batchCreateOssFilesApi, batchSignUrlApi } from '#/api/sys/file';
|
||||
|
||||
interface UploadResult {
|
||||
/** 文件访问URL(可直接用于 img src 等) */
|
||||
accessUrl: string;
|
||||
/** 存储路径(用于系统内引用) */
|
||||
storagePath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传单个文件到 OSS(通过统一文件系统)
|
||||
* @param file 文件对象
|
||||
* @param dir 保存目录,如 'product-images', 'shop-logos'
|
||||
*/
|
||||
export async function uploadFileToOssFromSystem(
|
||||
file: File,
|
||||
dir: string = 'general',
|
||||
): Promise<UploadResult> {
|
||||
const signRes = await batchSignUrlApi({
|
||||
files: [{ filename: file.name, fileHash: '' }],
|
||||
});
|
||||
|
||||
const fileInfo = signRes.files[0];
|
||||
if (!fileInfo) {
|
||||
throw new Error('签名响应为空');
|
||||
}
|
||||
|
||||
// 已存在则直接返回
|
||||
if (fileInfo.exists && fileInfo.accessUrl && fileInfo.storagePath) {
|
||||
return {
|
||||
accessUrl: fileInfo.accessUrl,
|
||||
storagePath: fileInfo.storagePath,
|
||||
};
|
||||
}
|
||||
|
||||
// 前端直传 OSS
|
||||
if (fileInfo.uploadUrl && fileInfo.uploadHeaders) {
|
||||
await fetch(fileInfo.uploadUrl, {
|
||||
method: 'PUT',
|
||||
headers: fileInfo.uploadHeaders,
|
||||
body: file,
|
||||
});
|
||||
}
|
||||
|
||||
// 通知后端创建文件记录
|
||||
const createRes = await batchCreateOssFilesApi({
|
||||
files: [
|
||||
{
|
||||
filename: file.name,
|
||||
fileHash: '',
|
||||
storagePath: fileInfo.storagePath || '',
|
||||
fileSize: file.size,
|
||||
mimeType: file.type,
|
||||
category: dir,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const firstFile = createRes[0];
|
||||
if (!firstFile) {
|
||||
throw new Error('文件记录创建失败');
|
||||
}
|
||||
|
||||
return {
|
||||
accessUrl: firstFile.accessUrl || '',
|
||||
storagePath: firstFile.storagePath || '',
|
||||
};
|
||||
}
|
||||
@@ -1,295 +1,10 @@
|
||||
/**
|
||||
* OSS文件上传工具
|
||||
* @deprecated 请使用 `#/utils/upload-file` 的 `uploadFile` / `uploadFiles`
|
||||
*/
|
||||
|
||||
import type { FileVO } from '#/api/sys/file/types';
|
||||
|
||||
import { message } from 'ant-design-vue';
|
||||
|
||||
import SparkMD5 from 'spark-md5';
|
||||
|
||||
import { batchCreateOssFilesApi, batchSignUrlApi } from '#/api/sys/file';
|
||||
|
||||
/**
|
||||
* 上传选项
|
||||
*/
|
||||
export interface UploadOptions {
|
||||
/** 文件分类 */
|
||||
category?: string;
|
||||
/** 错误提示消息 */
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算文件的MD5哈希值(使用 spark-md5,支持大文件分片计算)
|
||||
* @param file 文件对象
|
||||
* @returns 返回文件的MD5哈希值(十六进制字符串)
|
||||
*/
|
||||
function calculateFileHash(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const spark = new SparkMD5.ArrayBuffer();
|
||||
const chunkSize = 2 * 1024 * 1024; // 2MB per chunk
|
||||
let offset = 0;
|
||||
|
||||
function loadNext() {
|
||||
const slice = file.slice(offset, offset + chunkSize);
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = (e) => {
|
||||
spark.append(e.target?.result as ArrayBuffer);
|
||||
offset += chunkSize;
|
||||
if (offset < file.size) {
|
||||
loadNext();
|
||||
} else {
|
||||
resolve(spark.end());
|
||||
}
|
||||
};
|
||||
|
||||
reader.onerror = () => reject(new Error('文件哈希计算失败'));
|
||||
reader.readAsArrayBuffer(slice);
|
||||
}
|
||||
|
||||
loadNext();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用Header签名上传文件到OSS
|
||||
* @param file 要上传的文件
|
||||
* @param uploadUrl 上传URL(不含签名参数)
|
||||
* @param uploadHeaders Header签名信息(包含Authorization、Date、x-oss-date、Content-Type等)
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
async function uploadFileToOssWithHeaderSignature(
|
||||
file: File,
|
||||
uploadUrl: string,
|
||||
uploadHeaders: Record<string, string>,
|
||||
): Promise<void> {
|
||||
const headers: Record<string, string> = { ...uploadHeaders };
|
||||
const contentType =
|
||||
headers['Content-Type'] ?? headers['content-type'] ?? '';
|
||||
|
||||
// OSS4 预签名 PUT 与 Content-Type 严格一致;File 作 body 时浏览器会按 file.type 自动带头,易 403。
|
||||
const body =
|
||||
contentType !== '' ? await file.arrayBuffer() : file;
|
||||
if (contentType !== '') {
|
||||
headers['Content-Type'] = contentType;
|
||||
delete headers['content-type'];
|
||||
}
|
||||
|
||||
const response = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let detail = '';
|
||||
try {
|
||||
detail = (await response.text()).slice(0, 300);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
throw new Error(
|
||||
`上传失败: ${response.status} ${response.statusText}${detail ? ` — ${detail}` : ''}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到OSS(通过Header签名)
|
||||
* @param file 要上传的文件
|
||||
* @param options 上传选项
|
||||
* @param options.category 文件分类
|
||||
* @param options.errorMessage 错误提示消息
|
||||
* @returns 返回文件信息,包含文件ID
|
||||
*/
|
||||
export async function uploadFileToOss(
|
||||
file: File,
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info> {
|
||||
try {
|
||||
// 1. 计算文件哈希值
|
||||
const fileHash = await calculateFileHash(file);
|
||||
|
||||
// 2. 获取Header签名
|
||||
const signResponse = await batchSignUrlApi({
|
||||
files: [
|
||||
{
|
||||
filename: file.name,
|
||||
fileHash,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!signResponse.files || signResponse.files.length === 0) {
|
||||
throw new Error('获取签名失败');
|
||||
}
|
||||
|
||||
const signInfo = signResponse.files[0];
|
||||
if (!signInfo) {
|
||||
throw new Error('获取签名失败');
|
||||
}
|
||||
|
||||
// 3. 如果文件已存在,直接返回文件信息
|
||||
if (signInfo.exists && signInfo.fileInfo) {
|
||||
return signInfo.fileInfo;
|
||||
}
|
||||
|
||||
// 4. 如果文件不存在,使用Header签名上传到OSS
|
||||
if (!signInfo.uploadUrl) {
|
||||
throw new Error('未获取到上传URL');
|
||||
}
|
||||
if (!signInfo.uploadHeaders) {
|
||||
throw new Error('未获取到上传Header签名信息');
|
||||
}
|
||||
|
||||
await uploadFileToOssWithHeaderSignature(
|
||||
file,
|
||||
signInfo.uploadUrl,
|
||||
signInfo.uploadHeaders,
|
||||
);
|
||||
|
||||
// 5. 上传成功后,创建OSS文件记录
|
||||
// 使用签名响应中的 storagePath
|
||||
if (!signInfo.storagePath) {
|
||||
throw new Error('未获取到存储路径');
|
||||
}
|
||||
|
||||
const createResponse = await batchCreateOssFilesApi({
|
||||
files: [
|
||||
{
|
||||
filename: file.name,
|
||||
fileHash,
|
||||
storagePath: signInfo.storagePath,
|
||||
fileSize: file.size,
|
||||
mimeType: file.type,
|
||||
category: options?.category,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!createResponse || createResponse.length === 0) {
|
||||
throw new Error('创建文件记录失败');
|
||||
}
|
||||
|
||||
const fileInfo = createResponse[0];
|
||||
if (!fileInfo) {
|
||||
throw new Error('创建文件记录失败');
|
||||
}
|
||||
|
||||
return fileInfo;
|
||||
} catch (error) {
|
||||
console.error('文件上传失败:', error);
|
||||
const errorMsg = options?.errorMessage || '文件上传失败';
|
||||
message.error(errorMsg);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量上传文件到OSS(通过Header签名)
|
||||
* @param files 要上传的文件列表
|
||||
* @param options 上传选项
|
||||
* @param options.category 文件分类
|
||||
* @param options.errorMessage 错误提示消息
|
||||
* @returns 返回文件信息列表
|
||||
*/
|
||||
export async function uploadFilesToOss(
|
||||
files: File[],
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info[]> {
|
||||
try {
|
||||
// 1. 计算所有文件的哈希值
|
||||
const fileItems = await Promise.all(
|
||||
files.map(async (file) => ({
|
||||
filename: file.name,
|
||||
fileHash: await calculateFileHash(file),
|
||||
})),
|
||||
);
|
||||
|
||||
// 2. 批量获取Header签名
|
||||
const signResponse = await batchSignUrlApi({
|
||||
files: fileItems,
|
||||
});
|
||||
|
||||
if (!signResponse.files || signResponse.files.length === 0) {
|
||||
throw new Error('获取签名失败');
|
||||
}
|
||||
|
||||
const results: FileVO.Info[] = [];
|
||||
const filesToUpload: Array<{
|
||||
file: File;
|
||||
fileHash: string;
|
||||
signInfo: FileVO.FileSignInfo;
|
||||
}> = [];
|
||||
|
||||
// 3. 分类处理:已存在的文件和需要上传的文件
|
||||
for (let i = 0; i < signResponse.files.length; i++) {
|
||||
const signInfo = signResponse.files[i];
|
||||
const file = files[i];
|
||||
const fileItem = fileItems[i];
|
||||
if (!signInfo || !file || !fileItem) continue;
|
||||
|
||||
if (signInfo.exists && signInfo.fileInfo) {
|
||||
// 文件已存在,直接使用
|
||||
results.push(signInfo.fileInfo);
|
||||
} else if (signInfo.uploadUrl && signInfo.uploadHeaders) {
|
||||
// 文件不存在,需要上传
|
||||
filesToUpload.push({
|
||||
file,
|
||||
fileHash: fileItem.fileHash,
|
||||
signInfo,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 批量上传不存在的文件
|
||||
if (filesToUpload.length > 0) {
|
||||
await Promise.all(
|
||||
filesToUpload.map(({ file, signInfo }) => {
|
||||
if (!signInfo.uploadUrl) {
|
||||
throw new Error('未获取到上传URL');
|
||||
}
|
||||
if (!signInfo.uploadHeaders) {
|
||||
throw new Error('未获取到上传Header签名信息');
|
||||
}
|
||||
return uploadFileToOssWithHeaderSignature(
|
||||
file,
|
||||
signInfo.uploadUrl,
|
||||
signInfo.uploadHeaders,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
// 5. 批量创建OSS文件记录
|
||||
const createResponse = await batchCreateOssFilesApi({
|
||||
files: filesToUpload.map(({ file, signInfo, fileHash }) => {
|
||||
// 使用签名响应中的 storagePath
|
||||
if (!signInfo.storagePath) {
|
||||
throw new Error('未获取到存储路径');
|
||||
}
|
||||
return {
|
||||
filename: file.name,
|
||||
fileHash,
|
||||
storagePath: signInfo.storagePath,
|
||||
fileSize: file.size,
|
||||
mimeType: file.type,
|
||||
category: options?.category,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
if (createResponse && createResponse.length > 0) {
|
||||
results.push(...createResponse);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('文件上传失败:', error);
|
||||
const errorMsg = options?.errorMessage || '文件上传失败';
|
||||
message.error(errorMsg);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export {
|
||||
uploadFile as uploadFileToOss,
|
||||
uploadFiles as uploadFilesToOss,
|
||||
uploadFile,
|
||||
uploadFiles,
|
||||
} from './upload-file';
|
||||
export type { UploadOptions } from './upload-file';
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* 统一文件上传:按系统配置在 multipart(后端)与 direct(OSS 直传)间分流
|
||||
*/
|
||||
import type { FileVO } from '#/api/sys/file/types';
|
||||
|
||||
import { message } from 'ant-design-vue';
|
||||
import SparkMD5 from 'spark-md5';
|
||||
|
||||
import {
|
||||
batchCreateOssFilesApi,
|
||||
batchSignUrlApi,
|
||||
batchUploadFilesApi,
|
||||
} from '#/api/sys/file';
|
||||
import { useAppConfigStore } from '#/store/app-config';
|
||||
|
||||
export interface UploadOptions {
|
||||
/** 文件分类 */
|
||||
category?: string;
|
||||
/** 错误提示消息 */
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
function calculateFileHash(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const spark = new SparkMD5.ArrayBuffer();
|
||||
const chunkSize = 2 * 1024 * 1024;
|
||||
let offset = 0;
|
||||
|
||||
function loadNext() {
|
||||
const slice = file.slice(offset, offset + chunkSize);
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
spark.append(e.target?.result as ArrayBuffer);
|
||||
offset += chunkSize;
|
||||
if (offset < file.size) {
|
||||
loadNext();
|
||||
} else {
|
||||
resolve(spark.end());
|
||||
}
|
||||
};
|
||||
reader.onerror = () => reject(new Error('文件哈希计算失败'));
|
||||
reader.readAsArrayBuffer(slice);
|
||||
}
|
||||
|
||||
loadNext();
|
||||
});
|
||||
}
|
||||
|
||||
async function uploadFileToOssWithHeaderSignature(
|
||||
file: File,
|
||||
uploadUrl: string,
|
||||
uploadHeaders: Record<string, string>,
|
||||
): Promise<void> {
|
||||
const headers: Record<string, string> = { ...uploadHeaders };
|
||||
const contentType =
|
||||
headers['Content-Type'] ?? headers['content-type'] ?? '';
|
||||
|
||||
// OSS4 预签名 PUT 与 Content-Type 严格一致
|
||||
const body = contentType !== '' ? await file.arrayBuffer() : file;
|
||||
if (contentType !== '') {
|
||||
headers['Content-Type'] = contentType;
|
||||
delete headers['content-type'];
|
||||
}
|
||||
|
||||
const response = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let detail = '';
|
||||
try {
|
||||
detail = (await response.text()).slice(0, 300);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
throw new Error(
|
||||
`上传失败: ${response.status} ${response.statusText}${detail ? ` — ${detail}` : ''}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** multipart:经后端落盘/对象存储 */
|
||||
async function uploadViaMultipart(
|
||||
file: File,
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info> {
|
||||
const uploaded = await batchUploadFilesApi([file], options?.category);
|
||||
const first = uploaded[0];
|
||||
if (!first) {
|
||||
throw new Error('文件上传失败');
|
||||
}
|
||||
return {
|
||||
id: first.id,
|
||||
storageType: first.storageType,
|
||||
storagePath: first.storagePath,
|
||||
filename: first.filename,
|
||||
fileFormat: first.fileFormat,
|
||||
mimeType: first.mimeType,
|
||||
fileSize: first.fileSize,
|
||||
fileHash: first.fileHash,
|
||||
category: first.category,
|
||||
tags: first.tags,
|
||||
remark: first.remark,
|
||||
accessUrl: first.accessUrl,
|
||||
uploadTime: '',
|
||||
updateTime: '',
|
||||
};
|
||||
}
|
||||
|
||||
/** direct:签名直传 OSS 后入库 */
|
||||
async function uploadViaDirect(
|
||||
file: File,
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info> {
|
||||
const fileHash = await calculateFileHash(file);
|
||||
const signResponse = await batchSignUrlApi({
|
||||
files: [{ filename: file.name, fileHash }],
|
||||
});
|
||||
|
||||
const signInfo = signResponse.files?.[0];
|
||||
if (!signInfo) {
|
||||
throw new Error('获取签名失败');
|
||||
}
|
||||
|
||||
if (signInfo.exists && signInfo.fileInfo) {
|
||||
return signInfo.fileInfo;
|
||||
}
|
||||
|
||||
if (!signInfo.uploadUrl) {
|
||||
throw new Error('未获取到上传URL');
|
||||
}
|
||||
if (!signInfo.uploadHeaders) {
|
||||
throw new Error('未获取到上传Header签名信息');
|
||||
}
|
||||
if (!signInfo.storagePath) {
|
||||
throw new Error('未获取到存储路径');
|
||||
}
|
||||
|
||||
await uploadFileToOssWithHeaderSignature(
|
||||
file,
|
||||
signInfo.uploadUrl,
|
||||
signInfo.uploadHeaders,
|
||||
);
|
||||
|
||||
const createResponse = await batchCreateOssFilesApi({
|
||||
files: [
|
||||
{
|
||||
filename: file.name,
|
||||
fileHash,
|
||||
storagePath: signInfo.storagePath,
|
||||
fileSize: file.size,
|
||||
mimeType: file.type,
|
||||
category: options?.category,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const fileInfo = createResponse?.[0];
|
||||
if (!fileInfo) {
|
||||
throw new Error('创建文件记录失败');
|
||||
}
|
||||
return fileInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传单个文件(按系统配置自动选择 multipart / direct)
|
||||
*/
|
||||
export async function uploadFile(
|
||||
file: File,
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info> {
|
||||
try {
|
||||
const appConfig = useAppConfigStore();
|
||||
await appConfig.ensureLoaded();
|
||||
|
||||
if (appConfig.isDirectUpload) {
|
||||
return await uploadViaDirect(file, options);
|
||||
}
|
||||
return await uploadViaMultipart(file, options);
|
||||
} catch (error) {
|
||||
console.error('文件上传失败:', error);
|
||||
message.error(options?.errorMessage || '文件上传失败');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量上传(当前按文件串行,保持与单文件同一分流逻辑)
|
||||
*/
|
||||
export async function uploadFiles(
|
||||
files: File[],
|
||||
options?: UploadOptions,
|
||||
): Promise<FileVO.Info[]> {
|
||||
const results: FileVO.Info[] = [];
|
||||
for (const file of files) {
|
||||
results.push(await uploadFile(file, options));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/** @deprecated 使用 uploadFile */
|
||||
export const uploadFileToOss = uploadFile;
|
||||
/** @deprecated 使用 uploadFiles */
|
||||
export const uploadFilesToOss = uploadFiles;
|
||||
+2
-2
@@ -20,7 +20,7 @@ import { getAdFeeFieldsApi } from '#/api/ec/shop/ad-fee/apis';
|
||||
import { getShopPageApi } from '#/api/ec/shop';
|
||||
import { createImportTaskApi } from '#/api/ec/import/task';
|
||||
import { useImportTaskStore } from '#/store';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface FieldMappingItem {
|
||||
@@ -430,7 +430,7 @@ const handleCreateTask = async () => {
|
||||
createTaskSubmitting.value = true;
|
||||
message.loading('正在上传文件...', 0);
|
||||
const patchedFile = buildPatchedCsv();
|
||||
const fileInfo = await uploadFileToOss(patchedFile, {
|
||||
const fileInfo = await uploadFile(patchedFile, {
|
||||
category: 'ad-fee-import',
|
||||
errorMessage: '文件上传失败,请重试',
|
||||
});
|
||||
|
||||
+2
-2
@@ -34,7 +34,7 @@ import { createImportTaskApi } from '#/api/ec/import/task';
|
||||
import { getAllOrderStatusListApi } from '#/api/ec/order/status';
|
||||
import { getShopPageApi } from '#/api/ec/shop';
|
||||
import { useImportTaskStore } from '#/store';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import { createPatchedFile } from '../utils/skuCodePatch';
|
||||
|
||||
// 定义映射项数据结构
|
||||
@@ -1179,7 +1179,7 @@ const handleCreateTask = async () => {
|
||||
|
||||
// 先上传文件到 OSS(使用统一文件系统)
|
||||
message.loading('正在上传文件...', 0);
|
||||
const fileInfo = await uploadFileToOss(selectedFile.value, {
|
||||
const fileInfo = await uploadFile(selectedFile.value, {
|
||||
category: 'order-import',
|
||||
errorMessage: '文件上传失败,请重试',
|
||||
});
|
||||
|
||||
+3
-3
@@ -21,7 +21,7 @@ import dayjs from 'dayjs';
|
||||
|
||||
import { getCategoryTreeApi } from '#/api/ec/product/category';
|
||||
import { createProductApi, updateProductApi } from '#/api/ec/product';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import CategoryFormModal from '#/views/ec/product/category/components/CategoryFormModal.vue';
|
||||
import ProductCostSyncToOrdersModal from './ProductCostSyncToOrdersModal.vue';
|
||||
import ProductSkuCostDrawer from './ProductSkuCostDrawer.vue';
|
||||
@@ -873,7 +873,7 @@ async function uploadImageAndGetId(): Promise<number | undefined> {
|
||||
}
|
||||
|
||||
try {
|
||||
const fileInfo = await uploadFileToOss(newImageFile.value, {
|
||||
const fileInfo = await uploadFile(newImageFile.value, {
|
||||
category: 'product-main-image',
|
||||
errorMessage: '主图上传失败',
|
||||
});
|
||||
@@ -886,7 +886,7 @@ async function uploadImageAndGetId(): Promise<number | undefined> {
|
||||
|
||||
async function uploadSkuImageAndGetId(file: File): Promise<number | undefined> {
|
||||
try {
|
||||
const fileInfo = await uploadFileToOss(file, {
|
||||
const fileInfo = await uploadFile(file, {
|
||||
category: 'product-sku-image',
|
||||
errorMessage: 'SKU 图片上传失败',
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Button, Form, Input, message, Select } from 'ant-design-vue';
|
||||
|
||||
import { createShopApi, updateShopApi } from '#/api/ec/shop';
|
||||
import { getPlatformListApi } from '#/api/ec/platform';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
|
||||
interface Emits {
|
||||
(e: 'success'): void;
|
||||
@@ -239,7 +239,7 @@ async function uploadLogoAndGetId(): Promise<number | undefined> {
|
||||
}
|
||||
|
||||
try {
|
||||
const fileInfo = await uploadFileToOss(newLogoFile.value, {
|
||||
const fileInfo = await uploadFile(newLogoFile.value, {
|
||||
category: 'shop-logo',
|
||||
errorMessage: 'Logo上传失败',
|
||||
});
|
||||
|
||||
+6
-4
@@ -19,8 +19,8 @@ import dayjs from 'dayjs';
|
||||
import {
|
||||
createCompanyApi,
|
||||
updateCompanyApi,
|
||||
uploadCompanyLogoApi,
|
||||
} from '#/api/company';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
|
||||
interface Emits {
|
||||
(e: 'success'): void;
|
||||
@@ -271,11 +271,13 @@ async function uploadLogoAndGetId(): Promise<number | undefined> {
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await uploadCompanyLogoApi(newLogoFile.value);
|
||||
return response.id;
|
||||
const fileInfo = await uploadFile(newLogoFile.value, {
|
||||
category: 'company-logo',
|
||||
errorMessage: 'Logo上传失败',
|
||||
});
|
||||
return fileInfo.id;
|
||||
} catch (error) {
|
||||
console.error('Logo上传失败:', error);
|
||||
message.error('Logo上传失败');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Page } from '@vben/common-ui';
|
||||
import { Button, Form, Input, message, Spin, Upload } from 'ant-design-vue';
|
||||
|
||||
import { getUserInfoApi, updateUserInfoApi } from '#/api/sys/user';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
|
||||
defineOptions({ name: 'PersonalProfile' });
|
||||
|
||||
@@ -87,7 +87,7 @@ async function handleSubmit() {
|
||||
if (pendingAvatarFile.value) {
|
||||
avatarLoading.value = true;
|
||||
try {
|
||||
const fileInfo = await uploadFileToOss(pendingAvatarFile.value, {
|
||||
const fileInfo = await uploadFile(pendingAvatarFile.value, {
|
||||
category: 'user-avatar',
|
||||
errorMessage: '头像上传失败',
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user