mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 17:49:19 +08:00
refactor: 统一文件存储与上传流程,解耦 OSS 客户端、存储类型与前端上传模式
This commit is contained in:
@@ -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;
|
||||
Reference in New Issue
Block a user