's'
This commit is contained in:
49
app/api/community/upload/route.ts
Normal file
49
app/api/community/upload/route.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getApiUrlFromRequest, getPaymentConfig } from "@/config/services.config";
|
||||
|
||||
function resolvePayApiUrl(request: NextRequest): string {
|
||||
const payConfig = getPaymentConfig();
|
||||
const hostHeader = request.headers.get("host") || request.headers.get("x-forwarded-host");
|
||||
return ((hostHeader ? getApiUrlFromRequest(hostHeader) : null) || payConfig.apiUrl).replace(/\/$/, "");
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const formData = await request.formData().catch(() => null);
|
||||
if (!formData) {
|
||||
return NextResponse.json({ ok: false, error: "无效请求" }, { status: 400 });
|
||||
}
|
||||
|
||||
const user_id = (formData.get("user_id") as string)?.trim() || "";
|
||||
const file = formData.get("file") as File | null;
|
||||
|
||||
if (!user_id) {
|
||||
return NextResponse.json({ ok: false, error: "缺少 user_id" }, { status: 401 });
|
||||
}
|
||||
if (!file || !(file instanceof Blob)) {
|
||||
return NextResponse.json({ ok: false, error: "请选择图片" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const apiUrl = resolvePayApiUrl(request);
|
||||
const body = new FormData();
|
||||
body.append("user_id", user_id);
|
||||
body.append("file", file, file.name || "image");
|
||||
|
||||
const res = await fetch(`${apiUrl}/community/upload`, {
|
||||
method: "POST",
|
||||
body,
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
if (!res.ok) {
|
||||
return NextResponse.json(
|
||||
{ ok: false, error: data?.detail || "上传失败" },
|
||||
{ status: res.status }
|
||||
);
|
||||
}
|
||||
return NextResponse.json(data);
|
||||
} catch (error) {
|
||||
console.error("[community/upload] error:", error);
|
||||
return NextResponse.json({ ok: false, error: "服务异常" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user