63 lines
1.9 KiB
TypeScript
63 lines
1.9 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { writeFile, mkdir } from "fs/promises";
|
|
import { join } from "path";
|
|
import { prisma } from "@/lib/prisma";
|
|
import { randomUUID } from "crypto";
|
|
|
|
const UPLOAD_DIR = process.env.UPLOAD_DIR || "./uploads";
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const formData = await request.formData();
|
|
const file = formData.get("file") as File | null;
|
|
const nodeId = formData.get("nodeId") as string | null;
|
|
|
|
if (!file) {
|
|
return NextResponse.json(
|
|
{ error: "No file provided" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
if (!nodeId) {
|
|
return NextResponse.json(
|
|
{ error: "Node ID is required" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Ensure upload directory exists
|
|
const uploadPath = join(process.cwd(), UPLOAD_DIR);
|
|
await mkdir(uploadPath, { recursive: true });
|
|
|
|
// Generate unique filename
|
|
const ext = file.name.split(".").pop() || "bin";
|
|
const filename = `${randomUUID()}.${ext}`;
|
|
const filePath = join(uploadPath, filename);
|
|
|
|
// Write file to disk
|
|
const bytes = await file.arrayBuffer();
|
|
const buffer = Buffer.from(bytes);
|
|
await writeFile(filePath, buffer);
|
|
|
|
// Save attachment record in database
|
|
const attachment = await prisma.attachment.create({
|
|
data: {
|
|
nodeId,
|
|
filename,
|
|
originalName: file.name,
|
|
mimeType: file.type || "application/octet-stream",
|
|
size: file.size,
|
|
},
|
|
});
|
|
|
|
return NextResponse.json(attachment, { status: 201 });
|
|
} catch (error) {
|
|
console.error("Failed to upload file:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to upload file" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|