Design a reusable image uploader component for a design system. It is used for profile pictures, product photo galleries on a marketplace listing form, and attaching images to messages.
Requirements:
Discuss the component API, the upload pipeline (including client-side processing and how files reach storage), state management, error handling, accessibility and security.
An image uploader is a component with a pipeline behind it: acquire files → validate → process (decode, orient, resize, compress, strip metadata) → upload (direct to storage, chunked, resumable) → finalise (server verification, derived sizes) → hand an ID back to the form. The UI is a list of items each moving through that pipeline. The interview tests whether you can design the state machine, keep the main thread responsive while processing large photos, and make uploads robust and secure.
<input type="file" accept="image/*" multiple>), drag and drop onto a drop zone,
paste (Ctrl/Cmd+V), camera capture on mobile (capture attribute where appropriate).| Concern | Target |
|---|---|
| Feedback | thumbnail visible < 300 ms after selection, even for 12 MP photos |
| Main thread | no long tasks > 50 ms from decoding/resizing; typing elsewhere stays responsive |
| Bandwidth | upload ≤ ~1–2 MB per photo after client-side resize for typical listing images |
| Reliability | uploads resume after a dropped connection without restarting large files |
| Concurrency | 2–3 parallel uploads (tunable) so one file finishes quickly instead of all crawling |
| Accessibility | all actions keyboard operable; progress and errors announced; drag and drop never the only way |
| Security | server-side validation and re-encoding; uploads go to storage with scoped, expiring credentials |
Assume immediate upload, resizing allowed (keep originals optional), JPEG/PNG/WebP/HEIC input.
Do not stream large files through the application server. Instead:
POST /uploads) with file metadata.POST /uploads/:id/complete; the server verifies the object (size, magic bytes, decodes it),
re-encodes/strips metadata, triggers derived sizes, and returns an assetId.This keeps the app servers out of the data path, scales with storage, and lets the CDN/edge terminate uploads near the user.
| Part | Responsibility |
|---|---|
| Uploader UI (React) | drop zone, picker button, item list with thumbnails, progress, actions, errors |
| Upload store | items keyed by local ID with state machine status; derived aggregate status for the form |
| Validator | type sniffing, size, count, dimensions (after decode) |
| Processing worker | decode (createImageBitmap), orientation, resize on OffscreenCanvas, encode (convertToBlob), thumbnail generation |
| Upload scheduler | queue with concurrency limit, retries with backoff, pause on offline |
| Transport | XHR (for upload progress) or chunked/resumable protocol (multipart, tus) |
| Upload API | sessions, signed URLs, completion, asset IDs |
type LocalId = string; // crypto.randomUUID()
type UploadStatus =
| 'queued' // accepted, waiting for processing
| 'processing' // decoding/resizing in worker
| 'uploading'
| 'finalizing' // server verification
| 'done'
| 'error'
| 'canceled';
interface UploadItem {
id: LocalId;
file: File; // original, kept until done (for retry)
processed?: Blob; // resized output
previewUrl?: string; // object URL of a small thumbnail
width?: number;
height?: number;
status: UploadStatus;
progress: number; // 0..1 across bytes uploaded
bytesTotal: number;
error?: { code: UploadErrorCode; message: string; retryable: boolean };
session?: { uploadId: string; parts?: Array<{ partNumber: number; etag?: string }> };
assetId?: string; // server ID when done
attempt: number;
abort?: AbortController;
}
type UploadErrorCode =
| 'TYPE_NOT_ALLOWED' | 'TOO_LARGE' | 'TOO_SMALL_DIMENSIONS' | 'DECODE_FAILED'
| 'NETWORK' | 'SESSION_EXPIRED' | 'SERVER_REJECTED' | 'QUOTA';
interface UploaderState {
items: UploadItem[]; // ordered, order = gallery order
aggregate: 'idle' | 'busy' | 'error' | 'complete';
}
The form only cares about items.filter(i => i.status === 'done').map(i => i.assetId) and whether anything is still
busy. Non-serialisable things (File, AbortController) live in the store, not in form libraries' state.
interface ImageUploaderProps {
value?: UploadedAsset[]; // existing assets (editing a listing)
onChange?: (assets: UploadedAsset[]) => void; // fires when done items change or reorder
onStatusChange?: (s: UploaderState['aggregate']) => void; // lets the form disable submit
maxFiles?: number;
maxFileSize?: number; // bytes, before processing
accept?: string[]; // ['image/jpeg', 'image/png', 'image/webp', 'image/heic']
minDimensions?: { width: number; height: number };
resize?: false | { maxWidth: number; maxHeight: number; quality: number; format: 'image/jpeg' | 'image/webp' };
crop?: { aspect: number }; // e.g. 1 for avatars
concurrency?: number; // default 3
reorderable?: boolean;
label: string; // accessible name, e.g. "Listing photos"
description?: string; // constraints shown to all users
uploadAdapter?: UploadAdapter; // swap transport (tests, different backends)
}
interface UploadedAsset { assetId: string; url: string; width: number; height: number; alt?: string }
interface UploadAdapter {
createSession(meta: { name: string; type: string; size: number }): Promise<UploadSession>;
upload(session: UploadSession, blob: Blob, opts: { signal: AbortSignal; onProgress: (loaded: number) => void }): Promise<void>;
complete(session: UploadSession): Promise<UploadedAsset>;
}
A headless useImageUploader() hook exposes the store and actions (addFiles, retry, cancel, remove,
move) for teams with custom UIs (chat composer attachments look very different from a gallery grid).
POST /v1/uploads
{ "filename": "IMG_2041.HEIC", "contentType": "image/jpeg", "size": 1843302, "purpose": "listing-photo" }
201
{ "uploadId": "up_92ks", "strategy": "single", "url": "https://storage.example.com/...signed...",
"headers": { "Content-Type": "image/jpeg" }, "expiresAt": "2025-06-01T10:15:00Z" }
// For large files: strategy "multipart" with partSize and per-part URLs (or fetched lazily)
{ "uploadId": "up_92ks", "strategy": "multipart", "partSize": 5242880,
"parts": [{ "partNumber": 1, "url": "..." }, { "partNumber": 2, "url": "..." }] }
POST /v1/uploads/:uploadId/complete
{ "parts": [{ "partNumber": 1, "etag": "\"a1b2\"" }] }
200 { "assetId": "as_77x", "url": "https://img.example.com/as_77x?w=800", "width": 2048, "height": 1536 }
422 { "error": "SERVER_REJECTED", "reason": "not a valid image" }
purpose lets the server apply per-use-case limits and storage paths; the client never chooses the object key.
createImageBitmap(file, { imageOrientation: 'from-image' }) decodes off the main thread
and applies EXIF orientation; draw to an OffscreenCanvas at the target size (step down in halves or use
resizeQuality: 'high' where supported to avoid aliasing); convertToBlob({ type: 'image/webp', quality: 0.82 }).URL.createObjectURL(thumbnailBlob) for the preview, and revokeObjectURL on remove/unmount to avoid leaks.close() ImageBitmaps promptly.fetch has no upload progress events, so use XMLHttpRequest with xhr.upload.onprogress for
single-request uploads; for multipart, progress = sum of completed parts plus the current part's XHR progress.File (Files are storable in IndexedDB) to resume after a reload.offline, resume on online; show "Waiting for connection".beforeunload. Service-worker
Background Fetch is limited to downloads in practice; don't promise background uploads on the web.queued → processing → uploading → finalizing → done, with error and canceled reachable from
the active states. Actions are valid only in certain states (retry only from error).dragenter when the drag contains files (dataTransfer.types.includes('Files')); prevent
the browser's default of navigating to the dropped file anywhere on the page while the uploader is mounted.paste on the uploader and read clipboardData.files.Content-Type and Content-Length conditions; storage buckets
are private; public delivery goes through the image CDN.Content-Type set by the server and X-Content-Type-Options: nosniff; never serve SVG uploads inline from the main origin (script injection) — reject SVG or sanitise and
serve as an attachment.<label> for a hidden
<input type="file">, or a button calling input.click()); drag and drop is an enhancement, never the only path.aria-describedby.<progress> or role="progressbar" with aria-valuenow and a label ("IMG_2041.jpg
upload progress").Alt+Arrow), since drag to
reorder is inaccessible on its own (WCAG 2.5.7 dragging movements).Track per-upload: original size, processed size, processing time, upload duration and throughput, retries, failure
codes, browser/device. Alert on rising DECODE_FAILED (new phone formats) or SESSION_EXPIRED (clock skew, too
short expiry).
setInputFiles, network throttling and offline toggling mid-upload.Why upload immediately rather than on submit? The upload overlaps with form filling, so submit is instant. The cost is orphaned uploads when users abandon the form, solved by a TTL cleanup job.
How do you show progress accurately for a resized file? Progress is relative to the processed blob size, not the original. Show a "Preparing…" phase for processing so the bar doesn't sit at 0%.
How would you support pasting images from a screenshot tool? Handle paste events; clipboardData.files
contains a PNG; run it through the same pipeline with a generated filename.
How do you crop? Show a crop UI on a downscaled preview; store crop coordinates relative to the original dimensions; apply the crop in the worker (or send coordinates to the server to crop non-destructively).
What changes for video? No client re-encoding (too expensive in most cases); chunked resumable upload is
mandatory; generate a poster frame client-side from a <video> element for the preview; server transcodes.
Spotted a mistake or a rights concern? Report an issue