chatbot-template/app/(chat)/api/files/upload/route.ts

69 lines
1.9 KiB
TypeScript
Raw Normal View History

import { put } from "@vercel/blob";
import { NextResponse } from "next/server";
import { z } from "zod";
2024-10-11 18:00:22 +05:30
import { getSession } from "@/lib/auth";
2024-10-11 18:00:22 +05:30
2024-11-15 12:18:17 -05:00
// Use Blob instead of File since File is not available in Node.js environment
2024-10-11 18:00:22 +05:30
const FileSchema = z.object({
file: z
2024-11-15 12:18:17 -05:00
.instanceof(Blob)
2024-10-11 18:00:22 +05:30
.refine((file) => file.size <= 5 * 1024 * 1024, {
message: "File size should be less than 5MB",
2024-10-11 18:00:22 +05:30
})
2024-11-19 16:06:18 +03:00
// Update the file type based on the kind of files you want to accept
.refine((file) => ["image/jpeg", "image/png"].includes(file.type), {
message: "File type should be JPEG or PNG",
2024-11-19 16:06:18 +03:00
}),
2024-10-11 18:00:22 +05:30
});
export async function POST(request: Request) {
const session = await getSession();
2024-10-11 18:00:22 +05:30
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
2024-10-11 18:00:22 +05:30
}
if (request.body === null) {
return new Response("Request body is empty", { status: 400 });
2024-10-11 18:00:22 +05:30
}
try {
const formData = await request.formData();
const file = formData.get("file") as Blob;
2024-10-11 18:00:22 +05:30
if (!file) {
return NextResponse.json({ error: "No file uploaded" }, { status: 400 });
2024-10-11 18:00:22 +05:30
}
const validatedFile = FileSchema.safeParse({ file });
if (!validatedFile.success) {
const errorMessage = validatedFile.error.errors
.map((error) => error.message)
.join(", ");
2024-10-11 18:00:22 +05:30
return NextResponse.json({ error: errorMessage }, { status: 400 });
}
2024-11-15 12:18:17 -05:00
// Get filename from formData since Blob doesn't have name property
const filename = (formData.get("file") as File).name;
2024-10-11 18:00:22 +05:30
const fileBuffer = await file.arrayBuffer();
try {
const data = await put(`${filename}`, fileBuffer, {
access: "public",
2024-10-11 18:00:22 +05:30
});
return NextResponse.json(data);
} catch (_error) {
return NextResponse.json({ error: "Upload failed" }, { status: 500 });
2024-10-11 18:00:22 +05:30
}
} catch (_error) {
2024-10-11 18:00:22 +05:30
return NextResponse.json(
{ error: "Failed to process request" },
{ status: 500 }
2024-10-11 18:00:22 +05:30
);
}
}