0520发布文章

This commit is contained in:
zqlit committed 2026-05-21 00:27:35 +08:00
1 parent 993ac5581d
commit 013dce4f9f
89 files changed
+11923 -54

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
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 }
);
}
}