mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 08:29:19 +08:00
feat: 忘了干啥了
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
/**
|
||||
* OSS文件上传工具
|
||||
*/
|
||||
|
||||
import type { FileVO } from '#/api/system/file/types';
|
||||
|
||||
import { message } from 'ant-design-vue';
|
||||
|
||||
import { batchCreateOssFilesApi, batchSignUrlApi } from '#/api/system/file';
|
||||
|
||||
/**
|
||||
* 上传选项
|
||||
*/
|
||||
export interface UploadOptions {
|
||||
/** 文件分类 */
|
||||
category?: string;
|
||||
/** 错误提示消息 */
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算文件的SHA-256哈希值
|
||||
* @param file 文件对象
|
||||
* @returns 返回文件的SHA-256哈希值(十六进制字符串)
|
||||
*/
|
||||
async function calculateFileHash(file: File): Promise<string> {
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
|
||||
const hashArray = [...new Uint8Array(hashBuffer)];
|
||||
const hashHex = hashArray
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
return hashHex;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用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 response = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body: file,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`上传失败: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user