52 lines
1.7 KiB
TypeScript
52 lines
1.7 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { auth } from "@/auth";
|
|
import { uploadFile } from "@/lib/storage";
|
|
|
|
export const config = { api: { bodyParser: false } };
|
|
|
|
export const maxDuration = 60;
|
|
|
|
export async function POST(req: NextRequest) {
|
|
const session = await auth();
|
|
if (!session?.user) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
const formData = await req.formData();
|
|
const file = formData.get("file") as File | null;
|
|
const type = (formData.get("type") as string) || "videos";
|
|
|
|
if (!file) {
|
|
return NextResponse.json({ error: "No file provided" }, { status: 400 });
|
|
}
|
|
|
|
// Validate file type based on upload type
|
|
if (type === "image" && !file.type.match(/image\//)) {
|
|
return NextResponse.json({ error: "Only image files are accepted" }, { status: 400 });
|
|
}
|
|
|
|
if (type === "video" && !file.type.match(/video\//)) {
|
|
return NextResponse.json({ error: "Only video files are accepted" }, { status: 400 });
|
|
}
|
|
|
|
// Size limit: 500MB for images, 2GB for videos
|
|
const maxSize = type === "image" ? 500 * 1024 * 1024 : 2 * 1024 * 1024 * 1024;
|
|
if (file.size > maxSize) {
|
|
const maxSizeStr = type === "image" ? "500 MB" : "2 GB";
|
|
return NextResponse.json(
|
|
{ error: `File too large (max ${maxSizeStr})` },
|
|
{ status: 413 }
|
|
);
|
|
}
|
|
|
|
const buffer = Buffer.from(await file.arrayBuffer());
|
|
const result = await uploadFile(buffer, file.name, file.type, type);
|
|
|
|
return NextResponse.json({ url: result.url, key: result.key });
|
|
} catch (err) {
|
|
console.error("[upload]", err);
|
|
return NextResponse.json({ error: "Upload failed" }, { status: 500 });
|
|
}
|
|
}
|