File Upload Patterns
Quick Guide: Use drag-and-drop dropzones with fallback file inputs for uploads. Validate files client-side (MIME + magic bytes) AND server-side. For files >5MB use chunked uploads with progress tracking. Upload directly to S3 using presigned URLs to avoid server bottlenecks. Always implement proper accessibility with keyboard support and ARIA announcements. Use XHR (not fetch) for upload progress events.
<critical_requirements>
CRITICAL: Before Using This Skill
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type, named constants)
(You MUST validate files BOTH client-side AND server-side - client validation is UX only, not security)
(You MUST use magic bytes detection for security-critical uploads - MIME types and extensions can be spoofed)
(You MUST cleanup object URLs with URL.revokeObjectURL() to prevent memory leaks)
(You MUST provide keyboard support for dropzones - Enter/Space to open file dialog)
(You MUST use presigned URLs for cloud storage uploads - never proxy large files through your server)
</critical_requirements>
Auto-detection: file upload, dropzone, drag-drop, drag and drop upload, useDropzone, TUS protocol, presigned URL, multipart upload, file validation, magic bytes, MIME type, progress indicator, upload progress, XHR upload, S3 upload, file input, aria-label upload, chunked upload, resumable upload
When to use:
- Building file upload interfaces (single or multi-file)
- Implementing drag-and-drop upload areas
- Uploading to cloud storage directly from browser
- Validating file types before upload
- Showing upload progress with speed/ETA
- Handling large file uploads with chunking/resumable support
- Creating accessible file upload components
When NOT to use:
- Server-side file processing (use backend skills)
- File storage architecture (use infrastructure skills)
- Video/audio streaming (use media handling skills)
Detailed Resources:
- examples/core.md - Dropzone, file list, combined upload component
- examples/validation.md - MIME type, magic bytes, dimension validation
- examples/progress.md - Progress tracking, speed, abort, multi-file
- examples/preview.md - Image preview, thumbnails, EXIF orientation
- examples/s3-upload.md - Presigned URLs, multipart uploads
- examples/resumable.md - Chunked uploads, TUS protocol
- examples/accessibility.md - ARIA patterns, keyboard, announcements
- reference.md - Decision frameworks, anti-patterns, checklists
<philosophy>
Philosophy
File uploads are deceptively complex. A simple file input works for basic cases, but production apps need validation, progress feedback, error handling, and accessibility. The key insight is that client-side validation is for UX, not security - always validate on the server too.
Core Principles:
- Defense in depth - Validate extension + MIME type + magic bytes + server-side
- Progressive enhancement - Drag-drop enhances but doesn't replace click-to-browse
- Direct uploads - Use presigned URLs to upload to cloud storage directly, not through your server
- Chunked for reliability - Large files need chunking for resumability and progress
- Accessibility first - Keyboard navigation and screen reader support from day one
File Size Strategy:
| File Size | Upload Method | Progress UI | Storage Pattern |
|---|---|---|---|
| < 5MB | Single request | Spinner or bar | Direct presigned PUT |
| 5-50MB | Single request | Progress bar | Presigned PUT |
| 50MB-5GB | Chunked | Progress + ETA | Multipart presigned |
| > 5GB | Chunked + resumable | Progress + ETA + pause | Multipart required |
<patterns>
Core Patterns
Pattern 1: Drag-and-Drop Dropzone
Build a dropzone with drag-and-drop and fallback file input. Key elements:
- Track drag state with a counter ref (not boolean) to handle nested element events
role="button"+tabIndex={0}+ Enter/Space key handlers for keyboard access- Hidden
<input type="file">triggered by click/keyboard - Type validation via
acceptattribute plus runtime checking - Reset
event.target.value = ''after selection to allow re-selecting same file
// Key structure - full implementation in examples/core.md
export function FileDropzone({ onFilesSelected, accept, multiple, disabled }: FileDropzoneProps) {
const inputRef = useRef<HTMLInputElement>(null);
const dragCounterRef = useRef(0); // Handles nested element drag events
return (
<div
onDrop={handleDrop}
onDragEnter={() => { dragCounterRef.current++; setState('drag-over'); }}
onDragLeave={() => { dragCounterRef.current--; if (dragCounterRef.current === 0) setState('idle'); }}
onClick={() => inputRef.current?.click()}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') inputRef.current?.click(); }}
role="button"
tabIndex={disabled ? -1 : 0}
aria-label="File upload area. Click or drag files to upload."
>
<input ref={inputRef} type="file" hidden aria-hidden="true" tabIndex={-1} />
</div>
);
}
See examples/core.md for full implementation.
Pattern 2: File List Management Hook
Track multiple files with status, progress, and preview URLs:
// use-file-list.ts - full implementation in examples/core.md
interface FileWithId {
id: string;
file: File;
preview?: string;
status: "pending" | "uploading" | "success" | "error";
progress: number;
error?: string;
}
export function useFileList(options: UseFileListOptions = {}) {
const [files, setFiles] = useState<FileWithId[]>([]);
// addFiles returns { added, rejected } with rejection reasons
// removeFile cleans up object URLs via URL.revokeObjectURL()
// clearFiles revokes all object URLs before clearing
return {
files,
addFiles,
removeFile,
updateFile,
clearFiles,
hasFiles,
canAddMore,
};
}
Key: Always URL.revokeObjectURL() on remove and clear. Return rejected files with reasons for user feedback.
See examples/core.md for full hook.
Pattern 3: Upload Progress with XHR
The Fetch API does not support upload progress events. Use XHR:
// use-upload-progress.ts - full implementation in examples/progress.md
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (event) => {
if (event.lengthComputable) {
const speed = calculateRollingAverageSpeed(event.loaded, performance.now());
const remaining = (event.total - event.loaded) / speed;
setProgress({
loaded: event.loaded,
total: event.total,
percentage,
speed,
remainingTime: remaining,
});
}
});
Key: Use a rolling average (5 samples) for smooth speed display. Always provide abort capability via xhr.abort().
Note: Fetch streams measure bytes taken from your stream, not actual network transmission (Jake Archibald's analysis). A native fetch progress API is in development. Until then, use XHR.
See examples/progress.md for full hook and multi-file manager.
Pattern 4: Magic Bytes File Type Detection
MIME types and extensions can be spoofed. Read actual file bytes:
// file-type-detection.ts - full implementation in examples/validation.md
const FILE_SIGNATURES: FileSignature[] = [
{ mime: "image/jpeg", extension: "jpg", signature: [0xff, 0xd8, 0xff] },
{
mime: "image/png",
ex