Number 74: File upload with progress per file
Specification
- Catalogue
- No. 74 of 110
- Section
- Forms and inputs
- Interaction
- Loading, Feedback
- Element
- Form, Input
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
Drop photos or documents and watch each one upload, with retry for the one that failed.
The limits are stated before anyone picks a file, each file shows its own progress, and a failure is retried on its own instead of starting again.
Accepted types and size limit shown above the button; checked before upload. Rows enter in 200ms; progress bars fill per file. Try sample files shows a failure at 64% and a working Retry. Transfers are simulated here; a real build reads progress from the upload request.
Code
React and plain CSS"use client";
import { useEffect, useId, useRef, useState, type ChangeEvent, type DragEvent } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./file-upload.css";
const ACCEPT = ["image/jpeg", "image/png", "image/heic", "application/pdf"];
const ACCEPT_EXT = /\.(jpe?g|png|heic|pdf)$/i;
const MAX_MB = 10;
type Up = { id: number; name: string; size: number; progress: number; status: "uploading" | "done" | "failed" | "rejected"; reason?: string; failOnce?: boolean };
const mb = (bytes: number) => `${(bytes / 1048576).toFixed(1)} MB`;
function FileUploadDemo() {
const [files, setFiles] = useState<Up[]>([]);
const [over, setOver] = useState(false);
const [hidden, setHidden] = useState(0);
const nextId = useRef(1);
const input = useRef<HTMLInputElement>(null);
const chooseBtn = useRef<HTMLButtonElement>(null);
const list = useRef<HTMLUListElement>(null);
// Where focus goes after a row's own button disappears (Retry) or the row goes (Remove).
const focusAfter = useRef<{ row: number } | "choose" | null>(null);
const uid = useId();
const busy = files.some((f) => f.status === "uploading");
useEffect(() => {
const t = focusAfter.current;
if (!t) return;
focusAfter.current = null;
if (t === "choose") chooseBtn.current?.focus();
else list.current?.querySelector<HTMLElement>(`[data-row="${t.row}"] button:last-of-type`)?.focus();
}, [files]);
// One ticker drives every transfer while any is running. Simulated: a real
// build reads progress from the upload request instead.
useEffect(() => {
if (!busy) return;
const t = window.setInterval(() => {
setFiles((fs) =>
fs.map((f) => {
if (f.status !== "uploading") return f;
const p = Math.min(1, f.progress + 0.9 / Math.max(4, f.size / 300000));
if (f.failOnce && p >= 0.64) return { ...f, progress: 0.64, status: "failed", reason: "Connection dropped at 64%", failOnce: false };
return p >= 1 ? { ...f, progress: 1, status: "done" } : { ...f, progress: p };
}),
);
}, 120);
return () => window.clearInterval(t);
}, [busy]);
const add = (list: { name: string; size: number; type: string; failOnce?: boolean }[]) => {
const fresh: Up[] = list.map((f) => {
const typeOk = ACCEPT.includes(f.type) || ACCEPT_EXT.test(f.name);
const sizeOk = f.size <= MAX_MB * 1048576;
return {
id: nextId.current++,
name: f.name,
size: f.size,
progress: 0,
status: typeOk && sizeOk ? "uploading" : "rejected",
reason: !typeOk ? "Not a photo or PDF" : !sizeOk ? `${mb(f.size)}: the limit is ${MAX_MB} MB` : undefined,
failOnce: f.failOnce,
};
});
// The demo lists the latest four; say so rather than drop a chosen file silently.
setHidden(Math.max(0, files.length + fresh.length - 4));
setFiles((fs) => [...fs, ...fresh].slice(-4));
};
const onPick = (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files) add([...e.target.files].map((f) => ({ name: f.name, size: f.size, type: f.type })));
e.target.value = "";
};
const onDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
setOver(false);
add([...e.dataTransfer.files].map((f) => ({ name: f.name, size: f.size, type: f.type })));
};
const retry = (id: number) => {
focusAfter.current = { row: id };
setFiles((fs) => fs.map((f) => (f.id === id ? { ...f, status: "uploading", reason: undefined } : f)));
};
const remove = (id: number) => {
const i = files.findIndex((f) => f.id === id);
const near = files[i + 1] ?? files[i - 1];
focusAfter.current = near ? { row: near.id } : "choose";
setHidden(0);
setFiles((fs) => fs.filter((f) => f.id !== id));
};
return (
<div className="dm">
<div className="up">
<div
className="up-zone"
data-over={over || undefined}
onDragOver={(e) => {
e.preventDefault();
setOver(true);
}}
onDragLeave={() => setOver(false)}
onDrop={onDrop}
>
<p id={`${uid}-rules`}>
<strong>Photos of the job</strong>
<span>
JPG, PNG, HEIC or PDF, up to {MAX_MB} MB each. Drop them here or
</span>
</p>
<div className="up-actions">
<button ref={chooseBtn} type="button" className="dm-btn" data-variant="solid" onClick={() => input.current?.click()} aria-describedby={`${uid}-rules`}>
Choose files
</button>
<button
type="button"
className="dm-btn"
onClick={() =>
add([
{ name: "boiler-front.jpg", size: 2_200_000, type: "image/jpeg" },
{ name: "pipework.jpg", size: 3_500_000, type: "image/jpeg", failOnce: true },
{ name: "old-invoice.pdf", size: 400_000, type: "application/pdf" },
])
}
>
Try sample files
</button>
</div>
<input ref={input} type="file" multiple accept={`${ACCEPT.join(",")},.heic`} className="sr-only" tabIndex={-1} aria-hidden="true" onChange={onPick} />
</div>
<ul ref={list} className="up-list" aria-label="Files" aria-live="polite">
{files.map((f) => (
<li key={f.id} className="up-row" data-status={f.status} data-row={f.id}>
<div className="up-meta">
<span className="up-name">{f.name}</span>
<span className="up-state">
{f.status === "uploading" && `${Math.round(f.progress * 100)}% of ${mb(f.size)}`}
{f.status === "done" && `Uploaded, ${mb(f.size)}`}
{(f.status === "failed" || f.status === "rejected") && f.reason}
</span>
<span className="up-track" aria-hidden="true">
<i style={{ scale: `${f.progress} 1` }} />
</span>
</div>
{f.status === "failed" && (
<button type="button" className="up-act" onClick={() => retry(f.id)}>
Retry<span className="sr-only"> {f.name}</span>
</button>
)}
<button type="button" className="up-act" onClick={() => remove(f.id)} aria-label={`${f.status === "uploading" ? "Cancel" : "Remove"} ${f.name}`}>
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
<path d="M6 6l12 12M18 6 6 18" />
</svg>
</button>
</li>
))}
</ul>
{hidden > 0 && (
<p className="dm-small" role="status">
{hidden} earlier {hidden === 1 ? "file is" : "files are"} not listed: this demo shows the latest four.
</p>
)}
</div>
</div>
);
}
// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [{ click: ".dm-btn", text: "Try sample", wait: 4800 }];
export default function FileUploadEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="File upload with progress per file" tour={TOUR}>
<FileUploadDemo />
</PieceStage>
);
}