How would you handle file uploads through a form using a server action in Next.js?
Short answer
You read the uploaded file directly from the FormData object inside your server action using its field name, which gives you a File object that you can then process, save to disk, or upload to a cloud storage service, all without needing a separate API route.
Advertisement
AModel answer
You read the uploaded file directly from the FormData object inside your server action using its field name, which gives you a File object that you can then process, save to disk, or upload to a cloud storage service, all without needing a separate API route.
'use server';
export async function uploadAvatar(formData) {
const file = formData.get('avatar');
if (file && file.size > 0) {
const buffer = await file.arrayBuffer();
await saveToStorage(buffer, file.name);
}
}Real-world example
A user profile page lets someone upload a new avatar image directly through a server action, which reads the uploaded file and saves it to cloud storage without needing a separate API endpoint.
Likely follow-ups
- What is the maximum file size a server action can handle by default?
- How do you validate the file type before accepting an upload?
Related topics