Upload
Click or drag to select files; displays the file list and upload progress. Supports a real upload channel (action XHR / custom-request escape hatch), before-upload validation & transform, failure retry and cancel.
Basic Usage
Basic (select files)
Multiple & Limit
Multiple + max
max limits the maximum number of selectable files; accept filters file types. Files exceeding max are rejected and an oas-exceed-limit event is emitted.
Auto Upload
Auto upload (simulated progress)
With auto-upload, adding a file automatically starts uploading. When neither action nor custom-request is set, progress is simulated (built-in timer fallback, no network request); the progress bar reuses oas-progress.
Drag & Drop
Drag & drop upload
Drag files directly into the dashed area and release to add them (multiple supported); the area highlights while dragging. When disabled, the drag shows a not-allowed cursor and drops are ignored.
Picture Wall
list-type controls the list style: list (default, text rows), picture (rows with small thumbnails), picture-card (card thumbnail wall).
picture-card
Picture wall (picture-card)
Image files render thumbnails (URL.createObjectURL); non-image files show a file icon and name. Click a thumbnail to open the preview overlay (close with Esc or by clicking the mask); remove via the top-right ×, and hover shows preview/remove actions. A circular avatar card can be achieved with the CSS variable --oas-upload-card-radius: 50%.
On touch screens (pointer: coarse) there is no hover to rely on: the top-right remove × stays visible, the action overlay (preview/retry/cancel) stays visible on error/uploading cards, and the remove × / action buttons get a 44px hit target.
Remove, preview & max rejection
Picture wall · remove/preview/exceed
A 4th file is rejected by max="3" and triggers oas-exceed-limit with a warning; clicking a thumbnail triggers oas-preview.
picture rows with thumbnails
Rows with thumbnails (picture)
In list / picture modes, clicking the file name also opens the preview overlay (the name is a focusable button).
At the max
Reached max (pre-filled with 3)
Pre-filled to max="3"; further selections are rejected via oas-exceed-limit.
Disabled
Disabled
Real Upload Channel (action)
With action set, the built-in XHR channel is used: name (form file field, default file), data (extra form fields JSON), headers (request headers JSON), method (default POST) and with-credentials are passed through; progress/success/failure come from real XHR events.
action channel (with failure/retry demo)
The docs site has no real upload endpoint — /api/upload returns 404, which conveniently demonstrates the failure state: the row turns red with a retry button (⟳); clicking retry re-sends the request; while uploading you can click × to cancel (emits oas-cancel). Success emits oas-success (detail: { file, response }, where response is parsed JSON or raw text); failure emits oas-error (detail: { file, response, status }).
Error Summary & Batch Retry
An error summary bar renders conditionally above the list: N files failed to upload + Retry all + Clear errors (identical for every list-type; role="status" so screen readers announce it).
Retry all: each failed file goes through the existing per-file upload channel (oneoas-retryper file, followed by the usualoas-upload/oas-success/oas-errorsequence)Clear errors: removes the failed files from the list (oneoas-removeper file, a singleoas-changeat the end) — failed entries carry no recoverable data, so keeping them only leaves a red failure state- Script parity: the
retryAll()/clearErrors()public methods (for hosts that draw their own action area)
Failure summary (error bar + retry all)
This demo also targets the missing /api/upload: picking files shows the summary bar; "Retry all" re-sends the requests (the docs site still fails, so the bar stays); "Clear errors" drops the failed rows.
Custom Request Channel (custom-request)
Chunked uploads, object-storage direct upload, WebSocket and other non-standard channels are taken over by the custom-request function property (the component does not care about request strategy):
custom-request takes over the request
el.customRequest = ({ file, name, action, onProgress, onSuccess, onError }) => {
// send the request yourself; callback pacing is controlled by the host
onProgress({ percent: 60 })
onSuccess({ url: 'https://example.com/f.png' }) // or onError({ status: 500 })
return { abort: () => {/* cancel */} } // optional: a cancel button appears while uploading
}Manual Upload
Without auto-upload the component is in manual mode: after selecting files, call submit() (an alias of startUpload()) to upload them together.
Manual upload (submit together)
Before Upload (validation & transform)
The before-upload function property: return false to reject a file; return a new File to transform (rename/compress); async Promise is supported.
before-upload validation & transform
Image Crop (crop)
crop enables pre-upload image cropping. Activation conditions: list-type is picture / picture-card and accept includes image types — selecting / dropping / pasting an image file then opens a built-in lightweight crop dialog (self-drawn overlay, zero dependencies) instead of queueing directly:
- Move: drag the stage's empty area to pan the image; drag the crop frame to move it (arrow keys nudge when focused, Shift to speed up)
- Resize the frame: drag the bottom-right handle; set a fixed aspect ratio with
crop-aspect(e.g.1:1,16:9; invalid/missing = free ratio) - Zoom the image: mouse wheel on the stage, or the zoom in/out buttons (100% = cover baseline, up to 800%)
- Confirm: an offscreen canvas exports the cropped region at the source's natural resolution; the result file is queued in place of the original and
oas-cropis dispatched (detail: { file, blob }) - Cancel / Esc: closes without queueing; with multi-select, files are cropped one by one (cancel skips the current one and continues), non-image files queue directly
crop before upload (picture-card + 1:1)
Combined with before-upload, the hook runs first (validation/transform) and the transformed result enters cropping; queuing still respects max / max-size / replace (a cropped result may be smaller than the original — size limits are judged at queue time).
File Size Limit (max-size)
max-size accepts bytes or a unit form (512KB / 2MB / 1GB); it also accepts the IEC forms KiB / MiB / GiB / TiB / PiB / EiB plus TB, all parsed in base 1024 (1.5TiB, 2PiB, 1EiB all work). Oversized files are rejected with oas-exceed-limit (detail.type === 'size', including the maxSize in bytes). Invalid forms and boundaries: a non-empty but unparsable value (e.g. 2ZB) means "unlimited" and emits a one-time devWarn in development only (deduplicated by string); production builds shake the warning away, so in production an invalid value is silently unlimited (documented behavior). A product that overflows double precision (huge number × TB) and a numeric literal beyond the representable double range are both clamped to Number.MAX_SAFE_INTEGER; a positive form that rounds to 0 (e.g. 0.4B) is treated as 1 byte; an explicit 0 still means "unlimited".
Size display and units: file sizes in list rows, the
[data-item-size]binding, and the preview overlay use IEC units (B/KiB/MiB/GiB/TiB/PiB/EiB, base 1024) — theBtier rounds to an integer, other tiers use one fixed decimal; for example2048bytes renders as2.0 KiB, and1.5 GiBis no longer clamped to1536.0 MB. Themax-sizeinput formsKB/MB/GBare still parsed in base 1024; the numeric semantics match, only the display labels follow IEC (KiB/MiB/GiB).
max-size (100KB)
Replace on Exceed
With replace, exceeding the count limit no longer rejects: the oldest file is removed to make room (for max=1 / single-select this is "new replaces old" — no more "delete first, then select" for avatar-like scenarios).
replace (max=1, selecting a new file replaces the old)
Directory & Paste Upload
directory enables directory upload (sets webkitdirectory on the input; the list shows relative paths). paste enables paste upload (Ctrl+V clipboard files directly on the component — great for screenshots; off by default).
Directory upload (directory)
Paste upload (paste)
Mobile Camera Capture (capture)
capture passes through to the file input's capture (user front camera / environment rear camera; bare presence with no value = user; explicit "false" disables it). Mobile browsers open the camera directly when picking a file; desktop browsers ignore this hint per the HTML spec and behave as if it were absent.
Mobile camera capture (capture)
Trigger, Tip & Item Customization
slot="trigger": replaces the drop zone content (click/drag semantics stay on the zone container — the zone itself is the focusablerole="button"control, so do not nest interactive elements (buttons/links) inside the trigger content (nested-interactive is an axe violation); presentational content only)tipattribute ortemplate[slot="tip"]: secondary hint text below the zone (attribute wins)template[slot="item"]: cloned into everylist/picturerow;[data-item-name]/[data-item-size]bind the file name and size automatically (IEC units; theBtier rounds to an integer, other tiers use one decimal, e.g.2.0 KiB)
trigger / tip slots
item slot (custom list rows)
Echo Back & Hiding the List
- The
files/defaultFilesproperties accept{ name, url, size? }echo records (status done, preview uses the remote url) — the initial-value semantics for edit scenarios show-file-list="false"hides the built-in list, leaving only the trigger area (premise for host-drawn previews)
Echo back (defaultFiles)
Avatar (show-file-list=false + custom trigger + before-upload validation)
File List Persistence (storage-key)
storage-key turns on file list metadata persistence (opt-in, zero change by default): what goes into localStorage is metadata only ({ name, size, type, status, url? }) — file content is not persisted (a File body can be tens of MB; storage neither fits nor needs it). After a reload the list is restored in place, but a real upload still needs the file to be picked again.
doneentries come back as completed (valueis empty, no re-upload, no retry button) with a "persisted" hover hint; when the upload response carriesurl(ordata.url), thumbnails/previews keep using the server addresserror/ pending entries are restored as pending and oneoas-changeis dispatched (the file body is gone after a reload; silently resurrecting them as "done" would be unsafe — the host can guide the user to pick again)- Changing
storage-keyreloads the list from the new key immediately; removingstorage-keyonly stops writing (the restored/picked list stays as is) - Robustness: broken JSON, wrong version (
vmismatch) or wrong overall shape are silently ignored; when storage is unavailable (private mode / quota) writes degrade silently and the in-memory list keeps working
Persisted file list (storage-key)
Pick one or two files and reload the page: the list is still there (file names/sizes come from the metadata); "Clear saved list" wipes both the list and the local storage entry.
Events
Change events
Listen to oas-change / oas-remove / oas-upload / oas-progress:
oas-upload: progress,detail: { file, percent, status }(statusis onlyuploading/done; failures are not reported here but viaoas-error)oas-progress: upload progress callback (PRD P2),detail: { file, percent }— internal progress already drives the UI; this event adds the outbound channel (emitted by real / mock / custom-request channels alike, with 100 on success)oas-success/oas-error: upload success/failure (real channel),detail: { file, response, status? }oas-retry/oas-cancel: retry started / upload cancelled,detail: { file }oas-exceed-limit: rejection,detail: { files, max, total }(count) or{ files, type: 'size', maxSize, total }(size)oas-remove: file removed,detail: { file, index, replaced? }(replaced: truemeans removed by thereplacesemantics)oas-crop: crop confirmed,detail: { file, blob }(fileis the original file,blobthe offscreen canvas crop result)
Methods: submit() (manual upload), startUpload() (equivalent), abort(file?) (cancel one/all in-flight uploads).
oas-progress feedback
Third-party Composition Scenarios
These scenarios are not part of the component API; compose them via existing channels:
// Large-file chunking / object-storage direct upload: take over via custom-request
// (chunking strategy is a business decision)
el.customRequest = async ({ file, onProgress, onSuccess, onError }) => {
const chunks = sliceFile(file, 5 * 1024 * 1024) // chunk it yourself
for (let i = 0; i < chunks.length; i++) {
await uploadChunk(chunks[i], i)
onProgress({ percent: ((i + 1) / chunks.length) * 100 })
}
onSuccess(await assembleChunks(file))
}- Avatar cropping: covered by the built-in
cropchannel (see "Image Crop"); to use a third-party cropper instead, return the cropped newFilefrombefore-upload - List drag sorting: customize rows via the
itemslot + reorderfileswith a third-party dnd library - Circular avatar card: CSS variable
--oas-upload-card-radius: 50%(no separate enum)
required
required (native validation chain)
required drives the native validation chain (form-associated): when unfilled, checkValidity() returns false (valueMissing) and native form submission is blocked; it recovers to :valid once filled.
The current form value is available through the public value property for read/write: el.value returns the submittable File array ({name,url} echo records carry no file body and are not included; an empty array when there are no files); el.value = [file] replaces the whole file list (same controlled channel as the files property, no events dispatched).
Form-wide Validation
upload is a first-class oas-form control: when a rules entry matches the upload's name, the field value read by the form is the metadata JSON of submittable files ([{ name, size, type }]; '' for an empty list, matching the File-only semantics of value). So required agrees exactly with the native valueMissing check, and composite rules such as count/size can inspect the same JSON in a validator. On failure the message lands in the oas-form-item error slot (aria-invalid is synced onto the control), and scroll-to-first-error focuses and scrolls to the upload trigger.
The built-in max / max-size reject files before they enter the list (firing oas-exceed-limit). To surface an over-limit condition as a form-wide error (validated together with the other fields and located together), put the limit in a rule — the demo below validates count and per-file size that way.
Form-wide validation (required + count + size)
form.rules = {
attachments: [
{ required: true, message: 'Please upload at least 1 file' },
{
validator: (value) => {
const files = JSON.parse(value || '[]')
if (files.length > 2) return 'At most 2 files'
if (files.some((file) => file.size > 100 * 1024)) return 'Each file must be ≤ 100KiB'
return true
},
},
],
}Form Integration Notes
These four behaviors are current by design (not pending fixes) — align expectations before integrating:
oas-form'soas-values-changecovers upload (with the field value): upload'soas-changedetail carriesvaluealongsidefiles— the submittable file metadata JSON ([{ name, size, type }],''for an empty list), byte-identical toform.getValues()[name]. The form derivesoas-values-changefrom it (detail.valueanddetail.values[name]are that string); picking a file, removing one, or a storage restore each fire it once. Thatvalueis a derived read-only summary (file bodies cannot be rebuilt from metadata), so the form does not write it back; listen to upload's ownoas-changewhen you need per-Filedetail.clearErrors()reports pre-removal snapshot indices inoas-remove: each event'sindexis the list position at call start (not a live index during removal); for batch handling rely ondetail.file.- Form read/write asymmetry: the getter emits submittable
Fileentries only (the metadata JSON has nourl); the writer (valueproperty /initial-values/ theresetbaseline) expects echo records[{ name, url, size? }]. When reading the form value back intoinitial-values, do not include the upload field (records withouturlare dropped); maintain records withurlon the host side if you need echo-back. - Two restore paths (storage-key): restoring an all-
donelist (reload echo) fires no events — nooas-change/oas-upload, only the list echo plus a "saved" title hint per entry; restoring with anypending/errorentry downgrades them all topending(percent 0), fires oneoas-change, and does not start uploading — callstartUpload()/submit()from the host if needed.
API
oas-upload
Attributes
| Attribute | Description | Type | Default |
|---|---|---|---|
accept | Accepted file types | string | — |
action | Upload endpoint URL (real XHR channel; without it and customRequest, progress is simulated) | string | — |
auto-upload | Auto-simulate upload after adding | boolean | — |
capture | Mobile camera capture (user front / environment back; bare presence = user; "false" disables); ignored by desktop browsers per spec | string | — |
crop | Pre-upload image cropping (picture/picture-card + image accept): picked images open the built-in crop dialog first; the canvas crop result is queued on confirm | boolean | — |
crop-aspect | Fixed crop aspect ratio (e.g. 1:1, 16:9); invalid/missing = free ratio | string | — |
data | Extra form fields (JSON string, submitted with the file) | — | — |
directory | Directory upload (recursive folder intake) | boolean | — |
disabled | Disabled | boolean | — |
headers | Extra request headers (JSON string) | — | — |
list-type | List style: list (default) / picture (rows with thumbnails) / picture-card (card thumbnail wall) | string | list |
max | Maximum number of files | string | 0 |
max-size | Per-file size limit (bytes, or 2KB / 2KiB / 1MB / 1GiB / 1TiB / 1PiB / 1EiB / 2TB, all parsed in base 1024); unparsable non-empty values mean "unlimited" and only warn via devWarn in development (silent in production builds); when the multiplication result or the numeric literal itself exceeds the representable double range it is clamped to MAX_SAFE_INTEGER and 0.4B counts as 1 byte; over limit fires oas-exceed size form | string | — |
method | HTTP method (default POST) | string | POST |
multiple | Multiple selection | boolean | — |
name | Form field name for the file (default file) | string | — |
paste | Paste upload (off by default; clipboard files enter the list when on) | boolean | — |
replace | Replace semantics at max-count=1 (new file replaces the old instead of being rejected) | boolean | — |
required | Required marker (drives the native valueMissing validation chain; not passed through to the inner control) | boolean | — |
show-file-list | File list visibility ("false" hides it, keeping only the drop zone) | string | true |
storage-key | Persistence key for file list metadata (opt-in): stores name/size/type/status/url in localStorage (no file content); restores after reload — done entries come back completed (no re-upload, persisted hover hint), error/pending come back as pending with one oas-change; changing the key reloads immediately, removing it stops writing; broken JSON or a version mismatch is ignored | string | — |
tip | Drop-zone tip text (same as template[slot="tip"] for rich content) | string | — |
with-credentials | Cross-origin credentials | boolean | — |
Property (JS property; see each row for attribute reflection)
| Property | Description | Type | Default |
|---|---|---|---|
files | Controlled file list (property channel; assigning re-renders) | Array<File | UploadEchoFile> | [] |
value | Current value: the submittable File[] (file-body entries only; echo records without a body are excluded) | File[] | null | [] |
Methods
| Method | Signature | Description |
|---|---|---|
startUpload | startUpload(): void | Upload entry: the real channel (action XHR / custom-request) is used per file; with no channel it falls back to simulated progress |
submit | submit(): void | Alias of the manual upload entry (matching the common "submit" mental model) |
abort | abort(entry?: File): void | Cancel uploads: passing an entry cancels that one; omitting it cancels all in-flight uploads |
retryAll | retryAll(): void | Retries every failed file through the existing per-file upload channel (one oas-retry per file, then the usual progress/success/error events); a no-op when there is no real channel |
clearErrors | clearErrors(): void | Removes all failed entries from the list (one oas-remove per file, a single oas-change at the end); successful/pending entries are kept |
Events
| Event | Description |
|---|---|
oas-cancel | Upload cancelled, detail: { file } (cancel button on the item) |
oas-change | File list change, detail: { files, value } (files is the entry snapshot; value is the submittable file metadata JSON [{ name, size, type }], '' for an empty list, from which oas-form derives oas-values-change) |
oas-crop | Crop confirmed, detail: { file, blob } (file = original file, blob = offscreen canvas result) |
oas-error | Upload failed, detail: { file, response?, status? } (retry button appears) |
oas-exceed | [Compat alias] Same as oas-exceed-limit; will be removed later, detail: { files: rejected, max, total: next.length } | { files: sizeRejected, type: 'size', maxSize, total: next.length } |
oas-exceed-limit | Adding files rejected due to limit (canonical, aligned with checkbox-group/select/toggle-group), detail: { files, max, total }; emitted for both count and size rejections (size rejections also carry type: 'size' and maxSize) |
oas-preview | Preview overlay opened, detail: { file, url } |
oas-progress | Upload progress { file, percent }, emitted across all channels with 100 on success, detail: { file, percent: cur.percent } | { file, percent: 100 } | { file: f, percent: st.percent } |
oas-remove | File removed, detail: { file, index } |
oas-retry | Retry clicked, detail: { file } (re-upload after failure) |
oas-success | Upload succeeded, detail: { file, response } |
oas-upload | Upload progress, detail: { file, percent, status } |
Slots
| Name | Description |
|---|---|
template[slot="item"] | Custom file row/card ([data-item-name]/[data-item-size] bindings; IEC B/KiB/MiB… display, B tier rounds to an integer, other tiers use one decimal) |
template[slot="tip"] | Drop-zone tip rich content (tip attribute wins) |
template[slot="trigger"] | Self-drawn trigger-area template (native slot does not render template elements — cloned by the component; clicking the zone still opens the file picker) |
trigger | Replace the drop-zone content (zone semantics kept) |
CSS Variables
| CSS Variable | Default |
|---|---|
--oas-upload-card-radius | var(--oas-radius-md) |
⚠️ Three limitations of
template[slot="trigger"]: ① the template content is cloned into the shadow DOM — host-page stylesheets do not apply to cloned content (use inline styles / oas components / CSS variables instead); ② the clone is a static snapshot taken at component update() — template changes after connect do not auto-refresh (write the template before mounting the component, or nudge any attribute afterwards to trigger a re-sync); ③cloneNodedoes not carry event listeners —@click/addEventListenerbound on the template nodes are lost in the clone; use component events (oas-change, etc.) or delegate on the cloned zone container for interactivity.
Keyboard: Enter / Space on the drop zone opens the file picker; remove buttons are focusable; the preview overlay closes with Esc.