48 lines
1.7 KiB
TypeScript
48 lines
1.7 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getSession } from "@/lib/session";
|
|
import { writeFile, mkdir } from "fs/promises";
|
|
import path from "path";
|
|
import { sanitizeFilename } from "@/lib/upload";
|
|
|
|
function getUploadDirFar(root: string) {
|
|
const dir = process.env.UPLOAD_DIR || path.join(process.cwd(), "public", "uploads");
|
|
return path.join(dir, root.replace(/^\//, ""));
|
|
}
|
|
|
|
export async function POST(req: NextRequest) {
|
|
const session = await getSession();
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
const formData = await req.formData();
|
|
const file = formData.get("file") as File | null;
|
|
const subdirRaw = (formData.get("subdir") as string) || "";
|
|
const subdir = subdirRaw.replace(/[^a-zA-Z0-9_/-]/g, "");
|
|
|
|
if (!file) {
|
|
return NextResponse.json({ error: "Aucun fichier fourni" }, { status: 400 });
|
|
}
|
|
|
|
const originalName = sanitizeFilename(file.name);
|
|
const timestamp = Date.now();
|
|
const ext = path.extname(originalName) || ".bin";
|
|
const base = path.basename(originalName, ext);
|
|
const filename = `${timestamp}-${base}${ext}`;
|
|
|
|
const targetDir = getUploadDirFar(subdir);
|
|
await mkdir(targetDir, { recursive: true });
|
|
|
|
const bytes = Buffer.from(await file.arrayBuffer());
|
|
await writeFile(path.join(targetDir, filename), bytes);
|
|
|
|
const publicPath = `/uploads${subdir ? "/" + subdir : ""}/${filename}`;
|
|
|
|
return NextResponse.json({ url: publicPath, filename }, { status: 200 });
|
|
} catch (error) {
|
|
console.error("Upload error:", error);
|
|
return NextResponse.json({ error: "Erreur lors de l'upload" }, { status: 500 });
|
|
}
|
|
}
|