54 lines
1.8 KiB
TypeScript
54 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import fs from "fs";
|
|
import path from "path";
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const formData = await request.formData();
|
|
const file = formData.get("file") as File | null;
|
|
const dirPath = formData.get("dirPath") as string | null;
|
|
|
|
if (!file) {
|
|
return NextResponse.json({ error: "No file provided" }, { status: 400 });
|
|
}
|
|
if (!file.type.startsWith("image/")) {
|
|
return NextResponse.json({ error: "Only images allowed" }, { status: 400 });
|
|
}
|
|
|
|
const bytes = await file.arrayBuffer();
|
|
const buffer = Buffer.from(bytes);
|
|
|
|
// Determine upload directory
|
|
let uploadDir: string;
|
|
let isArticleFolder = false;
|
|
if (dirPath && fs.existsSync(dirPath)) {
|
|
uploadDir = dirPath;
|
|
isArticleFolder = true;
|
|
} else {
|
|
// Fallback to static/image
|
|
const year = new Date().getFullYear().toString();
|
|
uploadDir = path.join(process.cwd(), "..", "static", "image", year);
|
|
}
|
|
|
|
if (!fs.existsSync(uploadDir)) {
|
|
fs.mkdirSync(uploadDir, { recursive: true });
|
|
}
|
|
|
|
// Generate unique filename
|
|
const ext = file.name.split(".").pop() || "png";
|
|
const baseName = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
|
|
const fileName = `${baseName}.${ext}`;
|
|
const filePath = path.join(uploadDir, fileName);
|
|
fs.writeFileSync(filePath, buffer);
|
|
|
|
// Article folder: bare filename. Static fallback: absolute from Hugo root
|
|
const url = isArticleFolder ? fileName : `/image/${new Date().getFullYear()}/${fileName}`;
|
|
return NextResponse.json({ url, fileName });
|
|
} catch (error: unknown) {
|
|
return NextResponse.json(
|
|
{ error: error instanceof Error ? error.message : "Upload failed" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|