Files
gitlab-instance-0a899031_di…/app/api/upload-media/route.ts
2026-03-08 01:10:31 -06:00

73 lines
2.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NextRequest, NextResponse } from "next/server";
import * as Minio from "minio";
// mc alias list myminio: http://minioweb.hackrobot.cn:9035
const MINIO_ENDPOINT = process.env.MINIO_ENDPOINT || "minioweb.hackrobot.cn";
const MINIO_PORT = parseInt(process.env.MINIO_PORT || "9035", 10);
const MINIO_USE_SSL = process.env.MINIO_USE_SSL === "true";
const MINIO_BUCKET = process.env.MINIO_BUCKET || "hackrobot";
const MINIO_ACCESS_KEY = process.env.MINIO_ACCESS_KEY || "6i56HHfg4zPfYItCZtnp";
const MINIO_SECRET_KEY = process.env.MINIO_SECRET_KEY || "vDJCqEit3ejH5UmWKAZnvqhziNfbVsoOlBW12G8Q";
// 公开访问 URLhttps 无端口API 上传用 9035
const MINIO_PUBLIC_URL =
process.env.MINIO_PUBLIC_URL ||
`https://${MINIO_ENDPOINT}/${MINIO_BUCKET}`;
export async function POST(request: NextRequest) {
try {
const form = await request.formData();
const file = form.get("file");
const fileObj =
file instanceof File ? file : file instanceof Blob ? file : null;
if (!fileObj || fileObj.size === 0) {
return NextResponse.json(
{ ok: false, error: "请选择文件" },
{ status: 400 }
);
}
if (fileObj.size > 20 * 1024 * 1024) {
return NextResponse.json(
{ ok: false, error: "文件大小不能超过 20MB" },
{ status: 400 }
);
}
const client = new Minio.Client({
endPoint: MINIO_ENDPOINT,
port: MINIO_PORT,
useSSL: MINIO_USE_SSL,
accessKey: MINIO_ACCESS_KEY,
secretKey: MINIO_SECRET_KEY,
pathStyle: true,
region: process.env.MINIO_REGION || "china",
});
const ext =
(fileObj instanceof File ? fileObj.name : "").split(".").pop() ||
(fileObj.type?.startsWith("video/") ? "mp4" : "jpg");
const objectKey = `joins/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`;
const buffer = Buffer.from(await fileObj.arrayBuffer());
const contentType =
(fileObj as File).type || "application/octet-stream";
await client.putObject(MINIO_BUCKET, objectKey, buffer, buffer.length, {
"Content-Type": contentType,
});
const base = MINIO_PUBLIC_URL.replace(/\/$/, "");
const url = `${base}/${objectKey}`;
return NextResponse.json({ ok: true, url });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error("Upload media error:", e);
return NextResponse.json(
{ ok: false, error: `上传失败: ${msg}` },
{ status: 500 }
);
}
}