File Upload
Server actions for uploads, S3 integration, image processing, and progress tracking.
Overview
File uploads handle user-generated content in Next.js applications.
Key Concepts
- Server Actions — Handle file uploads
- S3 Uploads — Store files in cloud storage
- Image Processing — Resize and optimize uploads
- Progress Tracking — Show upload progress
- Validation — File type and size validation
Code Examples
// Server action for file upload
'use server';
import { put } from '@vercel/blob';
export async function uploadFile(formData) {
const file = formData.get('file');
if (!file) {
return { error: 'No file provided' };
}
// Validate file type
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
if (!allowedTypes.includes(file.type)) {
return { error: 'Invalid file type' };
}
// Validate file size (5MB max)
if (file.size > 5 * 1024 * 1024) {
return { error: 'File too large' };
}
const blob = await put(file.name, file, {
access: 'public',
contentType: file.type
});
return { url: blob.url };
}
// Client component with progress
'use client';
import { useState } from 'react';
function FileUpload() {
const [uploading, setUploading] = useState(false);
const [progress, setProgress] = useState(0);
const handleSubmit = async (e) => {
e.preventDefault();
setUploading(true);
const formData = new FormData(e.target);
const result = await uploadFile(formData);
setUploading(false);
if (result.error) {
alert(result.error);
}
};
return (
<form onSubmit={handleSubmit}>
<input type="file" name="file" accept="image/*" />
<button type="submit" disabled={uploading}>
{uploading ? `Uploading... ${progress}%` : 'Upload'}
</button>
</form>
);
}
Practice
Build a multi-file upload component with drag-and-drop and progress tracking.