Skip to
Keyboard shortcuts

Use the up and down arrow keys to move between items. Press Alt+Shift+K to open this list again.

Alpha version out now. The API may still change.

FileUpload

Attach files to a form. One native button opens the system file dialog, a drop zone is an extra for devices that drag, and every file is checked against your limits before it enters the list.

Package
@kvirn-ui/react
Testing
Automated. Core 0 of 2, Release 0 of 3

When to use it#

  • Use it when someone must attach documents, receipts or photos to an application or a report.
  • Dragging files onto the page is an extra, never the only way. Someone using only a keyboard, a screen reader (software that reads the screen aloud) or a voice control uses the button.
  • Say what to attach in the label and the description, and say the limits with FileUpload.Limits. Users can’t meet a limit they haven’t been told.
  • Decide whether refused files block the form. The component shows why a file was refused, but it never marks the Field invalid. That is your decision.
  • Not for choosing a value or a short answer: use a Listbox or a TextInput.
  • Not as a security check. The checks run on the device, so your server must check type, size and content again.

Example#

You can attach your doctor’s certificate and your receipts.

You can add up to 5 files. The files must be PDF, JPG, or PNG. Each file can be up to 10 MB.

Use cases#

Send the files with a plain form

Without upload, the files wait in the list and the component keeps the hidden file input equal to the list, dropped files included. Give the input a name, and a normal form submit sends them.

You can attach your doctor’s certificate and your receipts.

You can add up to 3 files. The files must be PDF, JPG, or PNG.

Props in this example:

Warning: Don't forget

A browser can’t put a file back in a file input after the page reloads. If your form reloads when a field has an error, people must choose the files again (3.3.7 Redundant Entry). Check every field in the browser first, or send the form without a reload.

Upload to your own server

KvirnUI sends nothing: you write upload. Report progress as a fraction from 0 to 1, and stop when the signal says so (it fires when the upload is cancelled or removed). The item then shows a progress bar, a Cancel button while it uploads, and Retry or Remove afterwards.

You can attach your doctor’s certificate and your receipts.

You can add up to 5 files. The files must be PDF, JPG, or PNG.

Props in this example:

Information: Did you know?

What upload resolves with is stored on the item as result, so you can read server ids in onFilesChange. Progress is never announced. Finished and failed uploads are announced together after a short pause.

Say why an upload failed

A bare error is never shown to people: the item says the upload failed, in neutral words, and offers Retry. To say more, reject with an error that sets retryable and a message that names the file and says what to do. retryable: false leaves only Remove, and FileUpload.ItemError shows the message next to the status.

You can attach your doctor’s certificate and your receipts.

The files must be PDF, JPG, or PNG.

Props in this example:

Add a check of your own

The built-in checks cover type, size, count, empty files, duplicates and folders. For anything else, return a message from validate and the file is refused with that text. It runs after the built-in checks.

You can attach your doctor’s certificate and your receipts.

The files must be PDF, JPG, or PNG.

Props in this example:

Warning: Don't forget

A client check is not security. Check the type, size and content again on your server, and strip the location data that photos can carry. See What you need to do.

One file, with a preview

With multiple off, a new file replaces the current one and the Trigger says “Replace file”. FileUpload.Preview shows a small thumbnail of an image, or the document icon for another file. It is decorative, so the name next to it stays the file’s name.

A photo is needed for your pass. Use a recent photo of your face, without a hat or sunglasses.

The file must be JPG or PNG. The file can be up to 5 MB.

Props in this example:

Say what is wrong when no file is attached

A file field is required when your form says so. Mark the Field required and invalid and render a Field.ErrorMessage that says what to do. The Trigger never has aria-required, because a button doesn’t allow it. A required Field shows no “(optional)” after its label, so the description should also say that a file is needed. Read the files from onFilesChange.

Attach your doctor’s certificate. A file is needed to send the application.

You can add up to 5 files. The files must be PDF, JPG, or PNG.

Props in this example:

Accessibility#

What it does for you#

  • APG pattern: none. There is no APG pattern for a file upload. The way in is a native <button> that opens the system file dialog, backed by a hidden native <input type="file">. A drop zone is an enhancement for devices that drag, never the only way in (2.1.1 Keyboard, level A; 2.5.7 Dragging Movements, level AA). Prior art: GOV.UK file upload and multiple file upload.
  • Deviations: none from APG. Rejected files are kept out of the list, and announcements are batched into one sentence.
  • Native elements used: <button> (Trigger, Cancel, Retry, Remove), <input type="file"> (Input), <progress> (Progress), <ul> and <li> (List, Item, and the lines of Rejections), <div> (Root, DropZone, Actions), <p> (DropHint, Summary, Status, ItemError).

A FileUpload lets someone attach files to a form. One button opens the system dialog. Files can also be dropped on a zone around it. Each file is checked against the limits, and a refused file never enters the list: it is named under the button, with how to fix it. Accepted files show in a list with their name, type, size and status, and can be uploaded through the consumer's own upload function, with a native progress bar. The library sends nothing anywhere.

PartElement / roleARIA / stateNotes
FileUpload.Root<div>, no rolenone. data-drag-active, data-full, data-invalid, data-disabledClass kv-file-upload. Takes the options (accept, multiple, maxFiles, maxFileSize, minFileSize, allowDuplicates, validate, upload, concurrency, autoUpload, disabled, messages) and callbacks
FileUpload.Trigger<button>aria-labelledby (the id of the text span inside the button, triggerTextId, then the Field label), aria-describedby (in this order: the Field's descriptions in DOM order, such as a help text and Limits; then the Field's error when invalid; then Rejections while there are any; then Summary when full), aria-invalidClass kv-button kv-file-upload-trigger. Carries the Field's control id, so the label and an error-summary link reach it. Never aria-required. At maxFiles: aria-disabled="true" and data-disabled, still focusable
FileUpload.Input<input type="file">aria-hidden="true", tabindex="-1", native disabled. Never requiredVisually hidden by inline style, never display: none. The Root adds one if you render none. name, capture and form pass through. accept and multiple come from the Root
FileUpload.DropZone<div>, no rolenone. data-droppable, data-dragging, data-invalid, data-disabledClass kv-file-upload-drop-zone. Not focusable, not clickable. The keyboard path is the Trigger inside it. The drop handlers are always attached
FileUpload.DropHint<p>none"or drop files here". Part of the zone. Not in the Trigger's name
FileUpload.Limits<p> (a description of the Field, like a Prose in it)referenced by the Trigger's aria-describedbyBuilt from the props, so it can't disagree with maxFiles, maxFileSize and accept
FileUpload.Rejections<div> with a <ul>referenced by the Trigger's aria-describedbyThe latest add's refused files, one line each: the file's name and how to fix it. Cleared by the next add, a removal and reset(). A cancelled dialog does not clear it
FileUpload.Summary<p>referenced by the Trigger's aria-describedby when the list is full"2 of 5 files added". At the limit it says what to do next
FileUpload.List<ul role="list">aria-labelledby the Field label, so it reads "Attachments, list, 3 items" (the label is the name only when the Field wraps the FileUpload)Class kv-file-upload-list. Holds accepted files only
FileUpload.Item<li>data-status (pending, uploading, complete, failed, cancelled), tabindex="-1"Class kv-file-upload-item. Focusable by script only: it takes focus when a button in it goes away
FileUpload.Name<bdi>noneThe file name. Wraps anywhere. A second file with the same name reads name (2)
FileUpload.Type, Size<span>noneA short label from the extension (PDF), never the MIME type. The size in decimal units with the locale's separator (2,4 MB)
FileUpload.Status<p>noneThe state in text (ready, uploading 40 %, uploaded, failed, cancelled), so colour and icons never carry it alone (1.4.1 Use of Color, level A)
FileUpload.ItemError<p>noneWhy a failed file failed and what to do, in text. Referenced by the item buttons’ aria-describedby while the item is failed (1.3.1 Info and Relationships, level A; 3.3.1 Error Identification, level A)
FileUpload.Progress<progress>named "Uploading report.pdf", value and max as whole percent. When the size is unknown it is not a <progress> but <span class="kv-progress-track" aria-hidden="true">Rendered only while the file is uploading, never focusable, never live. The decorative track loops while the upload runs and shows a still rest shape under reduced motion (2.2.2 Pause, Stop, Hide, level A)
Item buttons<button>Cancel: "Cancel upload of report.pdf". Retry: "Try again with report.pdf". Remove: "Remove report.pdf". Each name starts with its visible text (2.5.3 Label in Name, level A). aria-describedby: the item's Status, and its ItemError while it is failedOne action per state. Uploading: Cancel. Failed (retryable) or cancelled: Retry and Remove. Otherwise: Remove
useFileUploadthe same attributes, for your own elementsrootProps, triggerProps, inputProps, dropZoneProps, getItemProps, getProgressProps, getRemoveButtonProps, getCancelButtonProps, getRetryButtonProps, stateOptions as the Root. Spread each on its element

Rules, tested in file-upload.test.tsx:

  • One control. The Trigger is the only control that adds files and the only Tab stop for it. The native input is out of the accessibility tree and out of the Tab order, so browse mode and voice control see one control, and an error-summary link to the Field's id lands on a visible button (2.4.7 Focus Visible, level AA).
  • The Trigger's name points at a <span id="…-text"> that holds its visible text, then at the Field label (never at the button itself, which a native <label for> would outrank). With the hook, wrap your text in <span id={triggerTextId}>. Your own element must keep that span, or the name is only the label. The name starts with its visible text, then the Field label ("Choose files Attachments (optional)"), so a voice user can say "click Choose files" (2.5.3 Label in Name, level A) and two uploads on a page tell apart. A click on the label opens the dialog too, and does nothing at the limit.
  • No aria-required on the Trigger, and no required on the input. A button doesn't allow aria-required. A required Field shows through the missing "(optional)" marker, and the consumer's error says "required".
  • Every limit is checked here, because a drop and "All files" skip the browser's checks: type (by MIME type and extension), largest and smallest size, how many files, empty, duplicate (same name, size and last modified), folder, and the consumer's validate. A refused file never enters the list, never counts toward maxFiles, and never uploads. The Field is not marked invalid by it.
  • Adding appends, except with multiple off, where a new file replaces the old. A refused new file leaves the old one in place. With an upload function the input is reset after each add, so the same file can be chosen again. Without one, the input holds the list (through DataTransfer), so a plain form posts it.
  • Statuses are exposed as data-status and in text. A failure shows neutral words and never the raw error of the network. Only an error object that opts in (retryable, message) supplies text of its own.
  • Dragging is an extra (2.5.7 Dragging Movements, level AA). A file over the zone sets data-dragging and the hint says what dropping does; leaving the zone (not moving onto a child of it) clears it. A disabled zone shows no dragging state, answers dropEffect none and adds nothing.
  • Previews are decorative. The object URL made for one is revoked when its item goes away.
  • Retry reuses the stored File, so nobody has to find it in a phone's picker again.
  • The limits are said before anyone chooses (3.3.2 Labels or Instructions, level A): FileUpload.Limits, or a Field.HelpText in the Field (any description of the Field counts, so a Field.Prose does too). A development warning fires if accept, maxFiles or maxFileSize is set and neither exists.
  • Every part merges the consumer's class, handlers and refs with its own and carries its part class. Tested once, in the public API › every part merges class, handlers and refs, and carries its part class.
  • Dev warnings, each tested in development warnings: a part outside a Root, the limits not said (3.3.2 Labels or Instructions), a missing Announcer when a message has to be announced, and a browser that can't set the files of the input (DataTransfer). The types leave out aria-required and required on the Trigger and the input.

What you need to do#

  • Say the limits with FileUpload.Limits or a Field.HelpText in the Field, and give the Field a label that says what to attach.
  • Check on the server. A client check is not security: type, size and content are checked again where the file lands. Photos can carry location data, which the server should strip.
  • Decide whether refused files block the form. onFilesReject reports them as data. The Field's invalid and its message are yours.
  • Write upload. The library sends nothing. Report progress as a fraction from 0 to 1, honour the signal, and reject with an error object that has retryable and message to say more than the neutral text.
  • Translate your own text (the label and the description) and put them in a nested KvirnProvider with useLocale().localeProps on your own element where a locale isn't translated (3.1.2 Language of Parts, level AA).
  • Provide the Announcer (KvirnProvider). Without one, nothing is announced and a warning says so.
  • Don't make people choose a file twice (3.3.7 Redundant Entry, level A). A browser can't put a file back in a file input after a reload. Either upload on add (upload), keep the files on the server and show them again after a failed submit with a way to remove them, or check every field on the client (or submit with fetch) so a validation error never reloads the page.
  • 2.2.2 Pause, Stop, Hide (level A). The indicators (spinner, bar sheen, busy Button, job Toast, FileUpload track, Table busy sweep) move for as long as the wait lasts, which can be more than 5 s. prefers-reduced-motion: reduce is honoured and shows a still rest shape, but to meet WCAG 2.2.2 the app must also offer its own visible control that stops moving content (the library ships none) and applies the stop CSS. See "Moving indicators and WCAG 2.2.2" on the Theming page. The status text and the percent carry the wait.

Warning: Don't forget

Say the limits before people choose files (3.3.2 Labels or Instructions), and mount the KvirnProvider: without it nothing is announced (4.1.3 Status Messages).

Visual and modes#

  • The default theme draws the zone with a dashed edge where a precise pointer exists or a file is dragged over the page, and a solid heavier edge with a tint while a file is over it. That also holds in forced colours (an edge, not only a colour).
  • Each item has a status bar at its start edge, plus the status in text. In forced colours the bar is shown only on failed items.
  • Targets are at least 24 by 24 CSS pixels, and larger on devices with a coarse pointer such as a touch screen (2.5.8 Target Size (Minimum), level AA). Long names wrap anywhere, so a 120-character name doesn't scroll sideways at 320 CSS pixels (1.4.10 Reflow, level AA). RTL mirrors through logical properties.
  • Reduced motion removes every transition. The indeterminate track shows its still rest shape (2.2.2 Pause, Stop, Hide, level A).
  • On devices without a precise pointer there is no zone and no hint: only the button.
  • Focus indicator: the button and each item's Remove and Cancel buttons show the focus ring on keyboard focus (2.4.7 Focus Visible, AA), and nothing clips it. The page's sticky header is the consumer's to account for (2.4.11 Focus Not Obscured (Minimum), AA).
  • Text spacing (1.4.12 Text Spacing, AA): the text-spacing sweep applies the spacing to every story and fails on a box that clips its content. The reflow sweep runs every story at 320 CSS px and fails on horizontal overflow.

Warning: Don't forget

The upload track keeps moving for as long as an upload lasts. When that can be longer than 5 seconds beside other content, offer a visible control that stops it (2.2.2 Pause, Stop, Hide). See Moving indicators.

Focus management#

  • The Trigger keeps focus after the dialog closes and after files are added. Nothing else moves focus on an add.
  • Whenever a focused button goes away, focus never falls to body, and never lands on another button: a held or repeated Enter would delete a file the user didn't choose. - Cancel (when the upload finishes) and Retry (when it restarts) go away while their item stays: focus moves to that same item's <li tabindex="-1">. - Remove takes the item with it: focus moves to the next item's <li>, else the previous item's, else the Trigger. - Only a button that was removed from the page is replaced. A user who clicks away from a button that is still there keeps their place, however soon a progress tick renders (3.2.1 On Focus, level A).
  • Items are not Tab stops. A script focuses them only to keep focus in place.
  • A rejected file moves no focus. Its line is in the Trigger's description.
  • The drop moves no focus.

WCAG success criteria#

SCNameHow
1.3.1Info and Relationships (A)A real <button>, <ul>, <progress>, labels and descriptions through ids
1.4.1Use of Color (A)Status, errors and limits in text, with an icon, never colour alone
1.4.10Reflow (AA)Names wrap anywhere, the list is one column at 320 px
1.4.11Non-text Contrast (AA)Zone edge, status bar and focus ring pass the theme's contrast check
2.1.1Keyboard (A)The Trigger opens the native dialog
2.2.1Timing Adjustable (A)No timers end an upload
2.2.2Pause, Stop, Hide (A)The indeterminate track loops while the upload runs; reduced motion shows the rest shape. The app offers the stop control (Consumer responsibilities)
2.4.3Focus Order (A)Focus never falls to body after a removal, and stays on a non-destructive target
2.4.7Focus Visible (AA)The Trigger carries the Field's id, so an error link lands on a visible control
2.5.3Label in Name (A)Every button's name starts with its visible text
2.5.7Dragging Movements (AA)Dragging is never the only way: the Trigger
2.5.8Target Size (Minimum) (AA)At least 24 by 24 CSS pixels, larger on touch screens
3.2.2On Input (A)Adding a file submits nothing and moves no focus
3.3.1Error Identification (A)Each refused file is named in text
3.3.2Labels or Instructions (A)The limits are said before the choice
3.3.3Error Suggestion (AA)Each message says how to fix it
3.3.7Redundant Entry (A)Retry reuses the stored file; the round trip is the consumer's (Consumer responsibilities)
4.1.2Name, Role, Value (A)Native elements, the Trigger without aria-required
4.1.3Status Messages (AA)Batched, polite announcements that never replace one another

Keyboard#

Focus
native
Selection follows focus
n/a
Arrows wrap
n/a
Shortcuts
none
KeyWhereWhat happens
Tabbefore the fieldMoves focus to the Trigger. It is one stop. The hidden input and the drop zone are never stops
Test: file-upload.test.tsx › keyboard › Tab focuses the Trigger once
Tabon the TriggerMoves to the first button of the first item, or to the next element when the list is empty. Items are not stops, their buttons are
Test: file-upload.test.tsx › keyboard › Tab goes on to the item buttons
Shift+Tabon a button of an itemMoves back, to the Trigger after the first item
Test: file-upload.test.tsx › keyboard › Shift+Tab goes back to the Trigger
Enteron the TriggerOpens the system file dialog. Chosen files are added, and focus stays on the Trigger
Test: file-upload.test.tsx › keyboard › Enter opens the file dialog
Spaceon the TriggerOpens the system file dialog, as Enter
Test: file-upload.test.tsx › keyboard › Space opens the file dialog
Enter/Spaceon the Trigger, list fullDoes nothing: the Trigger is aria-disabled. It stays focusable and its description says why
Test: file-upload.test.tsx › keyboard › the Trigger does nothing at the limit
Enter/Spaceon RemoveRemoves the file. Focus moves to the next item, else the previous one, else the Trigger. The removal is announced
Test: file-upload.test.tsx › keyboard › Remove moves focus to the next item
Enter/Spaceon CancelCancels the upload. The file stays, with Retry and Remove. Focus moves to the item
Test: file-upload.test.tsx › keyboard › Cancel keeps the file and focuses the item
Enter/Spaceon RetryStarts the upload again with the same file. Focus moves to the item, since Retry goes away
Test: file-upload.test.tsx › keyboard › Retry restarts the upload
Escapeanywhere in the fieldNothing. The system dialog owns Escape, and a running upload is never ended by a key
Test: file-upload.test.tsx › keyboard › Escape and characters do nothing
Charactersanywhere in the fieldNothing. There is no type-ahead and no shortcut
Test: file-upload.test.tsx › keyboard › Escape and characters do nothing

Announcements#

FileUpload tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).

WhenWhat it saysMessage keyPoliteness
Files are added (now; after a dialog add, refused files are only counted, not named, because the Trigger's description names them)report.pdf added.fileUpload.fileAdded fileUpload.filesAddedPolite
The list is full after an add2 of 2 files added. Remove a file if you want to add a different one.fileUpload.summaryFullPolite
Files are refused2 files couldn't be added.fileUpload.filesRejectedPolite
A file is removedreport.pdf removed.fileUpload.fileRemovedPolite
Uploads start while not automatic (uploadAll())Uploading 3 files.fileUpload.uploadsStartedPolite
Uploads finish, after about one second of quiet (at most three)report.pdf uploaded.fileUpload.uploadComplete fileUpload.uploadsComplete fileUpload.allUploadsCompletePolite
Uploads fail, after about one second of quiet (at most three)report.pdf couldn't be uploaded.fileUpload.uploadFailed fileUpload.uploadsFailedPolite

Change the text#

For your whole app, pass messages to KvirnProvider. For one FileUpload, pass its messages prop.

<KvirnProvider messages={{ fileUpload: { fileAdded: 'report.pdf added.' } }}>

Warning: Don't forget

Announcements need a KvirnProvider around your app, outside any <form>, or an Announcer of your own. Without one nothing is announced, and a development warning says so.

API reference#

import { Field, FileUpload, useFileUpload } from '@kvirn-ui/react'

FileUpload.Root

Renders <div> that holds every part, the list, the upload queue and the announcements. It takes every attribute of a <div> and passes ref to it. Put it in a Field, so the Trigger gets its label. If you render no FileUpload.Input, it adds one. The default theme is described on Theming.

PropTypeDefaultDescription
acceptstring–The accepted types, comma separated: extensions (.pdf), MIME types and wildcards (image/*). It filters the file dialog and checks dropped files. Not security.
maxFileSizenumber–The largest file, in bytes. A larger one is refused as tooLarge.
minFileSizenumber–The smallest file, in bytes. A smaller one is refused as tooSmall.
maxFilesnumber–How many files the list holds. At the limit the Trigger is aria-disabled and says why. Ignored when multiple is off.
multiplebooleantrueOff is single-file mode: a new file replaces the current one and the Trigger text changes.
allowDuplicatesbooleanfalseOff refuses a file with the same name, size and last-modified time as one in the list.
validate(file: File) => string | null | undefined | void–Your own check, run last. A returned string refuses the file and is shown as its message.
upload(file: File, context: { signal: AbortSignal; onProgress: (fraction: number) => void }) => Promise<Result>–Sends the file wherever you want: KvirnUI makes no network calls. Report progress from 0 to 1, honour the signal, and reject to mark the file failed. Without it, files stay pending and go with the form.
concurrencynumber3How many uploads run at once.
autoUploadbooleantrueOff keeps files pending until uploadAll() is called.
previewsbooleanfalseGives image files a previewUrl on their item, for your own thumbnail. FileUpload.Preview makes its own, so you don’t need it for that.
disabledbooleanfalseNative disabled on the Trigger and the input, no item buttons, and a drop adds nothing. A disabled Field does the same.
onFilesChange(items: readonly FileUploadEntry<Result>[]) => void–Called when the list changes: a file is added or removed, an upload finishes or fails, or an item is retried. Not on every progress step.
onFilesReject(rejections: readonly FileUploadRejection[]) => void–Called when an add refused files, with the reasons as data. The component already shows and announces them.
messagesPartial<KvirnMessages["fileUpload"]>–Overrides the component’s strings for this instance.
Class or attributeValuesMeaning
kv-file-uploadalwaysThe part class. The default theme styles it.
data-drag-activepresent or absentA file is dragged over the page.
data-fullpresent or absentmaxFiles files are in the list.
data-invalidpresent or absentThe Field is invalid.
data-disabledpresent or absentThe Field or the disabled option disables it.

FileUpload.Trigger

Renders <button type="button">: the one control that adds files. It opens the system dialog, shows an upload icon before its text, carries the Field’s control id, and its name is its text and then the Field label. It never has aria-required.

PropTypeDefaultDescription
childrenReactNode–Replaces the text, which is “Choose files”, “Choose file” or “Replace file”.
Class or attributeValuesMeaning
kv-button kv-file-upload-triggeralwaysThe part classes.
data-fullpresent or absentmaxFiles files are in the list.
data-invalidpresent or absentThe Field is invalid. aria-invalid="true" is set with it.
data-disabledpresent or absentDisabled.
aria-disabled"true" or absentSet at maxFiles. The button stays focusable and its description says why.
aria-describedbyidsSet for you: the Field’s descriptions and error, then the Rejections, then the Summary when the list is full.

FileUpload.Input

Renders <input type="file">, visually hidden and out of the accessibility tree (aria-hidden, tabindex="-1", never display: none, never required). accept and multiple come from the Root.

PropTypeDefaultDescription
namestring–Posts the files with a plain form, under this name. capture and form also pass through.

FileUpload.DropZone

Renders <div> with no role that is never focusable: an extra for devices that drag. The keyboard path is the Trigger inside it.

Class or attributeValuesMeaning
kv-file-upload-drop-zonealwaysThe part class.
data-droppablepresent or absentThe zone is drawn: a precise pointer is attached, or a file is over the page.
data-draggingpresent or absentA file is over the zone itself. Never on a disabled zone.
data-invalidpresent or absentThe Field is invalid.
data-disabledpresent or absentDisabled.

FileUpload.DropHint

Renders <p> with the class kv-file-upload-drop-hint: “or drop files here”, shown while the zone is drawn and the list isn’t full. It is in no description.

PropTypeDefaultDescription
childrenReactNode–Replaces the hint, “or drop files here”.

FileUpload.Limits

Renders <p> with the class kv-file-upload-limits, built from maxFiles, accept and maxFileSize, so it can’t disagree with them. It renders nothing when no limit is set, and it is a description of the Field.

PropTypeDefaultDescription
childrenReactNode–Replaces the text built from accept, maxFiles and maxFileSize.

FileUpload.Rejections

Renders <div> with the class kv-file-upload-rejections, a heading line and a <ul> with one line per file the latest add refused. It renders nothing without refusals, is not a live region, and the Trigger’s description lists it while it shows. The next add, a removal or reset() clears it.

PropTypeDefaultDescription
childrenReactNode–Replaces the heading and one line per refused file.

FileUpload.Summary

Renders <p> with the class kv-file-upload-summary: “2 of 5 files added”, and at the limit what to do next. It renders nothing in single-file mode or with an empty list. The Trigger is described by it when the list is full.

PropTypeDefaultDescription
childrenReactNode–Replaces the text, for example “2 of 5 files added”.

FileUpload.List

Renders <ul role="list"> named by the Field label, with the class kv-file-upload-list. It renders only when there is a file.

PropTypeDefaultDescription
childrenReactNode | ((item: FileUploadEntry, index: number) => ReactNode)–A function that renders one FileUpload.Item per file, or your own nodes. Use item.id as the key.

FileUpload.Item

Renders <li> with the class kv-file-upload-item: one file. When Cancel or Retry goes away while the file stays, focus moves to this item. Remove moves focus to the next item, else the previous one, else the Trigger.

PropTypeDefaultDescription
itemFileUploadEntryRequiredThe file this item shows, from the List’s function: id, file, status, progress, error, result and previewUrl.
Class or attributeValuesMeaning
kv-file-upload-itemalwaysThe part class.
data-status"pending", "uploading", "complete", "failed" or "cancelled"The file’s state.
tabindex"-1"Only so a script can keep focus in place when a button goes away. It is not a Tab stop.

FileUpload.Preview

Renders <img alt=""> for an image the browser can decode, otherwise a <span> with the document icon. Both are decorative, because the name is next to them. The class is kv-file-upload-preview, and the image’s object URL is revoked when the item goes away.

PropTypeDefaultDescription
childrenReactNode–Replaces the document icon shown for a file that is not an image.

FileUpload.Name, .Type and .Size

Renders <bdi>, <span> and <span> with the classes kv-file-upload-name, kv-file-upload-type and kv-file-upload-size: the file name (with “(2)” when two files share one), the extension in capitals, and the size in the locale’s decimal units.

PropTypeDefaultDescription
childrenReactNode–Replaces the file’s name, type or size.

FileUpload.Status

Renders <p>: the state in words, never colour alone. The item’s buttons are described by it.

PropTypeDefaultDescription
childrenReactNode–Replaces the status text, for example “Uploading, 45 %”.
Class or attributeValuesMeaning
kv-file-upload-statusalwaysThe part class.
data-status"pending", "uploading", "complete", "failed" or "cancelled"The file’s state.

FileUpload.ItemError

Renders <p> with the class kv-file-upload-item-error, the error icon and a prefix that screen readers read and the default theme doesn’t show. It renders only while the item is failed, and the item’s buttons are described by it.

PropTypeDefaultDescription
childrenReactNode–Replaces your message from the rejected upload, or the neutral sentence.

FileUpload.Progress

Renders <progress> named “Uploading report.pdf”, with the class kv-file-upload-progress. It renders only while the file uploads, in whole percent. When the size is unknown it renders a decorative moving track (kv-progress-track, aria-hidden) instead of a <progress>. It is never announced.

FileUpload.Actions

Renders <div> with the class kv-file-upload-actions: a layout wrapper for an item’s buttons.

FileUpload.CancelButton, .RetryButton and .RemoveButton

Renders <button type="button">, one action per state: Cancel while the file uploads, Retry and Remove after a cancel or a failure (only Remove if the upload said it can’t be retried), and Remove otherwise. A button that doesn’t apply, or any button in a disabled Field, isn’t rendered. When the focused button goes away, focus never falls to the page or to another button.

PropTypeDefaultDescription
childrenReactNode–Replaces the visible text.
Class or attributeValuesMeaning
kv-button kv-file-upload-cancelclassOn the Cancel button. The Retry and Remove buttons have kv-file-upload-retry and kv-file-upload-remove.
aria-labeltextSet for you: the visible text, then the file name (“Remove report.pdf”).
aria-describedbyidsSet for you: the item’s Status, and its ItemError while the item has failed.

useFileUpload

Options

PropTypeDefaultDescription
acceptstring–The accepted types, comma separated: extensions (.pdf), MIME types and wildcards (image/*). It filters the file dialog and checks dropped files. Not security.
maxFileSizenumber–The largest file, in bytes. A larger one is refused as tooLarge.
minFileSizenumber–The smallest file, in bytes. A smaller one is refused as tooSmall.
maxFilesnumber–How many files the list holds. At the limit the Trigger is aria-disabled and says why. Ignored when multiple is off.
multiplebooleantrueOff is single-file mode: a new file replaces the current one and the Trigger text changes.
allowDuplicatesbooleanfalseOff refuses a file with the same name, size and last-modified time as one in the list.
validate(file: File) => string | null | undefined | void–Your own check, run last. A returned string refuses the file and is shown as its message.
upload(file: File, context: { signal: AbortSignal; onProgress: (fraction: number) => void }) => Promise<Result>–Sends the file wherever you want: KvirnUI makes no network calls. Report progress from 0 to 1, honour the signal, and reject to mark the file failed. Without it, files stay pending and go with the form.
concurrencynumber3How many uploads run at once.
autoUploadbooleantrueOff keeps files pending until uploadAll() is called.
previewsbooleanfalseGives image files a previewUrl on their item, for your own thumbnail. FileUpload.Preview makes its own, so you don’t need it for that.
disabledbooleanfalseNative disabled on the Trigger and the input, no item buttons, and a drop adds nothing. A disabled Field does the same.
onFilesChange(items: readonly FileUploadEntry<Result>[]) => void–Called when the list changes: a file is added or removed, an upload finishes or fails, or an item is retried. Not on every progress step.
onFilesReject(rejections: readonly FileUploadRejection[]) => void–Called when an add refused files, with the reasons as data. The component already shows and announces them.
messagesPartial<KvirnMessages["fileUpload"]>–Overrides the component’s strings for this instance.

Result

PropTypeDefaultDescription
rootPropsFileUploadRootPartProps–Spread on the root <div>.
dropZonePropsFileUploadDropZonePartProps–Spread on the drop zone <div>.
triggerPropsFileUploadTriggerPartProps–Spread on the Trigger <button>.
inputPropsFileUploadInputPartProps–Spread on the hidden <input type="file">.
rejectionsPropsFileUploadRejectionsPartProps–Spread on your rejections element, and call registerPart("rejections").
summaryPropsFileUploadSummaryPartProps–Spread on your summary element, and call registerPart("summary").
getItemProps(item) => FileUploadItemPartProps–Spread on each <li>.
getProgressProps(item) => FileUploadProgressPartProps–Spread on an item’s <progress>.
getStatusProps(item) => FileUploadStatusPartProps–Spread on an item’s status element.
getItemErrorProps(item) => FileUploadItemErrorPartProps–Spread on an item’s error element, shown while it is failed.
getRemoveButtonProps(item) => FileUploadItemButtonPartProps–Spread on an item’s Remove button.
getCancelButtonProps(item) => FileUploadItemButtonPartProps–Spread on an item’s Cancel button.
getRetryButtonProps(item) => FileUploadItemButtonPartProps–Spread on an item’s Retry button.
itemsreadonly FileUploadEntry[]–The accepted files, in order. Refused files never enter the list.
rejectionsreadonly FileUploadRejection[]–The files the latest add refused, as data.
rejectionLinesreadonly RejectionLine[]–One sentence per refused file: which file and what to do.
triggerTextstring–The Trigger’s text: choose, or replace in single-file mode with a file chosen.
triggerTextIdstring–The id of the element that holds the Trigger’s text, so its name starts with the visible text.
limitsTextstring–The limits that are set, as one text. Empty when none is set.
summaryTextstring–The summary, for example “2 of 5 files added”. Empty in single-file mode.
dropHintTextstring–The drop hint, or the dragging one while a file is over the zone.
getItemName(item) => string–The name the list shows, with “(2)” when two items share a file name.
getItemSize(item) => string–The size in the provider’s locale, in decimal units.
getItemType(item) => string–The extension in capitals, never the MIME type.
getItemStatusText(item) => string–The status as text.
getItemErrorText(item) => string | undefined–A failed upload’s text: yours, else a neutral one. Undefined unless the item is failed.
getItemActions(item) => { cancel: boolean; retry: boolean; remove: boolean }–Which buttons an item shows: one action per state.
messagesFileUploadMessages–The resolved fileUpload messages.
labelIdstring | undefined–The Field label’s id, for aria-labelledby on the list. Undefined outside a Field.
isMultipleboolean–Whether more than one file is allowed.
isDisabledboolean–Whether it is disabled.
isInvalidboolean–Whether the Field is invalid.
isFullboolean–Whether maxFiles files are in the list.
isDraggingboolean–Whether a file is dragged over the zone.
isDragActiveboolean–Whether a file is dragged over the page.
isDroppableboolean–Whether the zone is drawn: a precise pointer is attached, or a file is over the page.
add(files, source?) => FileUploadAddResult–Checks and adds files like the dialog or a drop does. Returns who was accepted and refused.
remove(id: string) => void–Removes an item, cancelling its upload first, and announces it.
cancel(id: string) => void–Cancels an upload.
retry(id: string) => void–Starts a failed or cancelled upload again.
uploadAll() => void–Starts every pending upload, for autoUpload off, and announces how many.
reset() => void–Empties the list and cancels every upload. Focus in the list goes to the Trigger.
registerPart(part) => () => void–Tells the hook a part is rendered, so the Trigger’s description lists it. Call it in a layout effect.
isPartRegistered(part) => boolean–Whether that part is rendered.

Strings

These are the default texts in @kvirn-ui/i18n.

For your whole app, pass messages to KvirnProvider. For one FileUpload, pass its messages prop.

A visible text and the name of its button change together: override remove and removeFile as a pair, or the name no longer starts with its visible text. The label and the description are yours, because they say what to attach and why.

Message keyParametersDefault text in EnglishUsed for
chooseFiles–Choose filesThe Trigger’s text with multiple.
chooseFile–Choose fileThe Trigger’s text in single-file mode with nothing chosen.
replaceFile–Replace fileThe Trigger’s text in single-file mode with a file chosen.
dropHintmultipleor drop files hereThe hint next to the Trigger on devices with a mouse.
dropHintActivemultipleDrop the files to add themThe hint while a file is over the zone.
limitsMaxFilescountYou can add up to 5 files.Limits: how many files.
limitsTypesallowed multipleThe files must be .pdf or .jpg.Limits: which types.
limitsMaxSizelimit multipleEach file can be up to 10 MB.Limits: how large.
summarycount3 files addedThe Summary without maxFiles.
summaryOfMaxcount maxFiles2 of 5 files addedThe Summary with maxFiles.
summaryFullmaxFiles5 of 5 files added. Remove a file if you want to add a different one.The Summary at the limit, with what to do next. It also ends the announcement of the add that filled the list.
rejectedHeadingcount1 file couldn’t be added:The first line of the Rejections.
statusReady–Added. It will be sent with the formAn item whose destination is the form.
statusQueued–Waiting to uploadAn item waiting for an upload slot.
statusUploading–UploadingAn upload with no known size.
statusUploadingPercentpercentUploading, 45%An upload with a known size.
statusComplete–UploadedA finished upload.
statusFailed–Upload failedA failed upload.
statusCancelled–Upload cancelledA cancelled upload.
typeUnknown–Unknown typeThe Type part when the file has no extension.
remove–RemoveThe visible text of the Remove button.
cancel–CancelThe visible text of the Cancel button.
retry–Try againThe visible text of the Retry button.
duplicateNamename numberimage.jpg (2)A file name when two items share it.
errorTypename allowednotes.txt isn’t a type of file we can accept. Choose a file in .pdf or .jpg format.Refused: not an accepted type.
errorTooLargename size limitscan.pdf is 12 MB. Choose a file that is 10 MB or smaller. To make a photo or scan smaller, save or scan it again at a lower resolution.Refused: too large.
errorTooSmallname size limitscan.pdf is 500 byte. Choose a file that is at least 1 kB.Refused: too small.
errorEmptynameempty.pdf is empty. Check that you chose the right file.Refused: the file has no content.
errorTooManyname maxFilesreceipt.pdf wasn’t added. You can add up to 5 files. Remove a file if you want to add a different one.Refused: the list is full.
errorDuplicatenamereceipt.pdf is already in the list.Refused: the same file is already in the list.
errorFoldernameDocuments is a folder. Open the folder and choose the files in it.Refused: a folder was dropped.
uploadFailedMessagenameWe couldn’t upload report.pdf. If it keeps failing, contact us.A failed upload that supplies no text of its own. Neutral: it never says why.
rejectedFilePositionposition total messageFile 2 of 3, image.jpg isn’t a type of file we can accept.Starts a refusal line for a file that shares its name with another in the same selection.
removeFilenameRemove report.pdfThe Remove button’s name. It starts with the visible text.
cancelFilenameCancel upload of report.pdfThe Cancel button’s name.
retryFilenameTry again with report.pdfThe Retry button’s name.
uploadingFilenameUploading report.pdfThe progress bar’s name.
fileAddednamereport.pdf added.Announced: one file was added.
filesAddedcount3 files added.Announced: several files were added.
filesRejectedcount2 files couldn’t be added.Announced: files were refused.
uploadsStartedcountUploading 3 files.Announced: uploads started.
uploadCompletenamereport.pdf uploaded.Announced: one upload finished.
uploadsCompletecount3 files uploaded.Announced: several uploads finished.
allUploadsCompletecountAll 3 files uploaded.Announced: a batch emptied the queue with no failure.
uploadFailednamereport.pdf couldn’t be uploaded.Announced: one upload failed.
uploadsFailedcount2 files couldn’t be uploaded.Announced: several uploads failed.
fileRemovednamereport.pdf removed.Announced: a file was removed.
announcementForFieldlabel messageAttachments: 2 files uploaded.Wraps an announcement with the Field label when several FileUploads are mounted.

Known issues#

  • HEIC photos (a photo format iPhones can use): whether Safari converts to JPEG for accept=".jpg" in every path needs a check on your own device.
  • Client-side limits can be bypassed. The server must check again.
  • Under React's <Activity mode="hidden"> the effect cleanup resets the list and aborts running uploads. Keep a FileUpload mounted while a form is hidden.
  • The Trigger's name is read from the text span and the Field label. A test asserts the name. Firefox and WebKit are not run automatically.

Information: Did you know?

Add the items that apply to your service to your accessibility statement, with the workaround. Test photos from iPhones against your own limits: HEIC, the photo format iPhones can use, is the known issue.

Testing#

The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.

AT + browser + OSAgent checkHuman checkResultNotes
Automated (re-runnable tests)
axe, WCAG 2.2 A and AA, every story, 4 themespassn/apassfile-upload.stories.tsx, every story, 4 themes
Markup and ARIA (roles, names, ids, states)passn/apassfile-upload.test.tsx (axe and role, name and state): a native button named by its own text then the Field label, with the Field control id
Keyboard contract rows (Vitest browser)passn/apass11 rows, each names a test in file-upload.test.tsx
Focus order and managementpassn/apassfile-upload.test.tsx: adding files does not move focus
Display modes (forced colours, 320px reflow, text spacing, reduced motion)passn/apassthe four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI
Core (required for beta)
NVDA + Chrome + Windowspendingpendingpending
VoiceOver + Safari + iOSpendingpendingpending
Release (before 1.0 and each minor)
JAWS + Chrome + Windowspendingpendingpending
TalkBack + Chrome + Androidpendingpendingpending
VoiceOver + Safari + macOSpendingpendingpending

What to check#

With a screen reader and the keyboard, try:

  • Tab to the button: its name (its text, then the label) and the limits are read.
  • Enter opens the file dialog. Choose an allowed file, one that is too big and one of the wrong type.
  • "Added" is read for the good one, a count for the refused ones, and the refusals can be read under the button.
  • A file's Remove button has the file name. After Enter, focus moves to the next file, else the previous, else the button.
  • A slow upload: the finish is heard, with no progress read-out. Cancel one: Retry and Remove appear and focus is on the item.
  • With the list full, the button says why it does nothing and is still reachable.