52 lines
1.2 KiB
TypeScript
52 lines
1.2 KiB
TypeScript
/**
|
|
* MinIO 客户端封装 - 上传、下载
|
|
*/
|
|
|
|
import * as Minio from "minio";
|
|
import { getMinioConfig } from "./config";
|
|
|
|
export function getMinioClient(): Minio.Client {
|
|
const cfg = getMinioConfig();
|
|
|
|
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;
|
|
}
|
|
|
|
export async function uploadBuffer(
|
|
buffer: Buffer,
|
|
objectKey: string,
|
|
contentType: string = "application/octet-stream"
|
|
): Promise<UploadResult> {
|
|
const cfg = getMinioConfig();
|
|
|
|
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 };
|
|
}
|
|
|
|
export function generateObjectKey(ext: string): string {
|
|
const cfg = getMinioConfig();
|
|
const prefix = cfg.uploadPrefix.replace(/\/$/, "");
|
|
return `${prefix}/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`;
|
|
}
|