Next.js File Upload with Progress
Upload files in Next.js using server actions with streaming progress, file size validation, MIME type checking, and chunked transfer to handle large files.
Code
export async function uploadFile(formData: FormData) {
const file = formData.get('file') as File;
if (file.size > 10 * 1024 * 1024) {
throw new Error('File too large (max 10MB)');
}
const allowed = ['image/png', 'image/jpeg', 'application/pdf'];
if (!allowed.includes(file.type)) {
throw new Error('Unsupported file type');
}
const buffer = Buffer.from(await file.arrayBuffer());
await fs.writeFile(`uploads/${file.name}`, buffer);
return { url: `/uploads/${file.name}`, size: file.size };
}