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

72 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-11-14 12:16:05 -05:00
import { put } from '@vercel/blob';
import { NextResponse } from 'next/server';
import { z } from 'zod';
2024-10-11 18:00:22 +05:30
2024-11-14 12:16:05 -05:00
import { auth } from '@/app/(auth)/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, {
2024-11-14 12:16:05 -05:00
message: 'File size should be less than 5MB',
2024-10-11 18:00:22 +05:30
})
.refine(
(file) =>
2024-11-14 12:16:05 -05:00
['image/jpeg', 'image/png', 'application/pdf'].includes(file.type),
2024-10-11 18:00:22 +05:30
{
2024-11-14 12:16:05 -05:00
message: 'File type should be JPEG, PNG, or PDF',
}
2024-10-11 18:00:22 +05:30
),
});
export async function POST(request: Request) {
const session = await auth();
if (!session) {
2024-11-14 12:16:05 -05:00
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
2024-10-11 18:00:22 +05:30
}
if (request.body === null) {
2024-11-14 12:16:05 -05:00
return new Response('Request body is empty', { status: 400 });
2024-10-11 18:00:22 +05:30
}
try {
const formData = await request.formData();
2024-11-15 12:18:17 -05:00
const file = formData.get('file') as Blob;
2024-10-11 18:00:22 +05:30
if (!file) {
2024-11-14 12:16:05 -05:00
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)
2024-11-14 12:16:05 -05:00
.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, {
2024-11-14 12:16:05 -05:00
access: 'public',
2024-10-11 18:00:22 +05:30
});
return NextResponse.json(data);
} catch (error) {
2024-11-14 12:16:05 -05:00
return NextResponse.json({ error: 'Upload failed' }, { status: 500 });
2024-10-11 18:00:22 +05:30
}
} catch (error) {
return NextResponse.json(
2024-11-14 12:16:05 -05:00
{ error: 'Failed to process request' },
{ status: 500 }
2024-10-11 18:00:22 +05:30
);
}
}