68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
/**
|
||
* MinIO 客户端封装 - 上传、下载等操作
|
||
* 通过 getMinioConfig() 获取配置,支持主题覆盖
|
||
*/
|
||
|
||
import * as Minio from "minio";
|
||
import { getMinioConfig } from "./config";
|
||
import { getThemeConfig } from "@/config/site.config";
|
||
|
||
/** 获取 MinIO 客户端实例(使用主题配置) */
|
||
export function getMinioClient(): Minio.Client {
|
||
const theme = getThemeConfig();
|
||
const cfg = getMinioConfig(theme.services?.minio);
|
||
|
||
return new Minio.Client({
|
||
endPoint: cfg.endPoint,
|
||
port: cfg.port,
|
||
useSSL: cfg.useSSL,
|
||
accessKey: cfg.accessKey,
|
||
secretKey: cfg.secretKey,
|
||
pathStyle: true,
|
||
region: cfg.region,
|
||
});
|
||
}
|
||
|
||
export interface UploadResult {
|
||
url: string;
|
||
objectKey: string;
|
||
}
|
||
|
||
/**
|
||
* 上传文件到 MinIO
|
||
* @param buffer 文件内容
|
||
* @param objectKey 对象键(含路径,如 joins/xxx.jpg)
|
||
* @param contentType MIME 类型
|
||
*/
|
||
export async function uploadBuffer(
|
||
buffer: Buffer,
|
||
objectKey: string,
|
||
contentType: string = "application/octet-stream"
|
||
): Promise<UploadResult> {
|
||
const theme = getThemeConfig();
|
||
const cfg = getMinioConfig(theme.services?.minio);
|
||
|
||
if (!cfg.enabled) {
|
||
throw new Error("MinIO 存储未启用");
|
||
}
|
||
|
||
const client = getMinioClient();
|
||
await client.putObject(cfg.bucket, objectKey, buffer, buffer.length, {
|
||
"Content-Type": contentType,
|
||
});
|
||
|
||
const url = `${cfg.publicUrl}/${objectKey}`;
|
||
return { url, objectKey };
|
||
}
|
||
|
||
/**
|
||
* 生成上传用的对象键
|
||
* @param ext 文件扩展名
|
||
*/
|
||
export function generateObjectKey(ext: string): string {
|
||
const theme = getThemeConfig();
|
||
const cfg = getMinioConfig(theme.services?.minio);
|
||
const prefix = cfg.uploadPrefix.replace(/\/$/, "");
|
||
return `${prefix}/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`;
|
||
}
|