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 };
}How it works
Next.js File Upload with Progress keeps everything in the function uploadFile.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. When the guard condition holds, Error is thrown rather than a bogus value returned.
Returns a newly built value, leaving the inputs as they were.
Caveats
- The guard
file.size > 10 * 1024 * 1024short-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
The entry-point signature is export async function uploadFile(formData: FormData)
The surface worth importing is uploadFile; the helpers around it are private to the snippet.
Core lines
return { url: `/uploads/${file.name}`, size: file.size };
const buffer = Buffer.from(await file.arrayBuffer());
await fs.writeFile(`uploads/${file.name}`, buffer);
FAQ
- Does `uploadFile` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Is there a failure path for bad input?
- Validation comes first — `Error` marks the failure at `file.size > 10 * 1024 * 1024`, before any partial work happens.
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `uploadFile` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.