Skip to content

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 (one oas-retry per file, followed by the usual oas-upload / oas-success / oas-error sequence)
  • Clear errors: removes the failed files from the list (one oas-remove per file, a single oas-change at 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

js
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)

Start upload

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-crop is 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) — the B tier rounds to an integer, other tiers use one fixed decimal; for example 2048 bytes renders as 2.0 KiB, and 1.5 GiB is no longer clamped to 1536.0 MB. The max-size input forms KB / MB / GB are 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 focusable role="button" control, so do not nest interactive elements (buttons/links) inside the trigger content (nested-interactive is an axe violation); presentational content only)
  • tip attribute or template[slot="tip"]: secondary hint text below the zone (attribute wins)
  • template[slot="item"]: cloned into every list / picture row; [data-item-name] / [data-item-size] bind the file name and size automatically (IEC units; the B tier 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 / defaultFiles properties 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.

  • done entries come back as completed (value is empty, no re-upload, no retry button) with a "persisted" hover hint; when the upload response carries url (or data.url), thumbnails/previews keep using the server address
  • error / pending entries are restored as pending and one oas-change is 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-key reloads the list from the new key immediately; removing storage-key only stops writing (the restored/picked list stays as is)
  • Robustness: broken JSON, wrong version (v mismatch) 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)

Clear saved list

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 } (status is only uploading / done; failures are not reported here but via oas-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: true means removed by the replace semantics)
  • oas-crop: crop confirmed, detail: { file, blob } (file is the original file, blob the 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:

js
// 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 crop channel (see "Image Crop"); to use a third-party cropper instead, return the cropped new File from before-upload
  • List drag sorting: customize rows via the item slot + reorder files with 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)

Submit (scroll to first error)
js
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's oas-values-change covers upload (with the field value): upload's oas-change detail carries value alongside files — the submittable file metadata JSON ([{ name, size, type }], '' for an empty list), byte-identical to form.getValues()[name]. The form derives oas-values-change from it (detail.value and detail.values[name] are that string); picking a file, removing one, or a storage restore each fire it once. That value is a derived read-only summary (file bodies cannot be rebuilt from metadata), so the form does not write it back; listen to upload's own oas-change when you need per-File detail.
  • clearErrors() reports pre-removal snapshot indices in oas-remove: each event's index is the list position at call start (not a live index during removal); for batch handling rely on detail.file.
  • Form read/write asymmetry: the getter emits submittable File entries only (the metadata JSON has no url); the writer (value property / initial-values / the reset baseline) expects echo records [{ name, url, size? }]. When reading the form value back into initial-values, do not include the upload field (records without url are dropped); maintain records with url on the host side if you need echo-back.
  • Two restore paths (storage-key): restoring an all-done list (reload echo) fires no events — no oas-change / oas-upload, only the list echo plus a "saved" title hint per entry; restoring with any pending / error entry downgrades them all to pending (percent 0), fires one oas-change, and does not start uploading — call startUpload() / submit() from the host if needed.

API ​

oas-upload ​

Attributes ​

AttributeDescriptionTypeDefault
acceptAccepted file typesstring—
actionUpload endpoint URL (real XHR channel; without it and customRequest, progress is simulated)string—
auto-uploadAuto-simulate upload after addingboolean—
captureMobile camera capture (user front / environment back; bare presence = user; "false" disables); ignored by desktop browsers per specstring—
cropPre-upload image cropping (picture/picture-card + image accept): picked images open the built-in crop dialog first; the canvas crop result is queued on confirmboolean—
crop-aspectFixed crop aspect ratio (e.g. 1:1, 16:9); invalid/missing = free ratiostring—
dataExtra form fields (JSON string, submitted with the file)——
directoryDirectory upload (recursive folder intake)boolean—
disabledDisabledboolean—
headersExtra request headers (JSON string)——
list-typeList style: list (default) / picture (rows with thumbnails) / picture-card (card thumbnail wall)stringlist
maxMaximum number of filesstring0
max-sizePer-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 formstring—
methodHTTP method (default POST)stringPOST
multipleMultiple selectionboolean—
nameForm field name for the file (default file)string—
pastePaste upload (off by default; clipboard files enter the list when on)boolean—
replaceReplace semantics at max-count=1 (new file replaces the old instead of being rejected)boolean—
requiredRequired marker (drives the native valueMissing validation chain; not passed through to the inner control)boolean—
show-file-listFile list visibility ("false" hides it, keeping only the drop zone)stringtrue
storage-keyPersistence 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 ignoredstring—
tipDrop-zone tip text (same as template[slot="tip"] for rich content)string—
with-credentialsCross-origin credentialsboolean—

Property (JS property; see each row for attribute reflection) ​

PropertyDescriptionTypeDefault
filesControlled file list (property channel; assigning re-renders)Array<File | UploadEchoFile>[]
valueCurrent value: the submittable File[] (file-body entries only; echo records without a body are excluded)File[] | null[]

Methods ​

MethodSignatureDescription
startUploadstartUpload(): voidUpload entry: the real channel (action XHR / custom-request) is used per file; with no channel it falls back to simulated progress
submitsubmit(): voidAlias of the manual upload entry (matching the common "submit" mental model)
abortabort(entry?: File): voidCancel uploads: passing an entry cancels that one; omitting it cancels all in-flight uploads
retryAllretryAll(): voidRetries 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
clearErrorsclearErrors(): voidRemoves all failed entries from the list (one oas-remove per file, a single oas-change at the end); successful/pending entries are kept

Events ​

EventDescription
oas-cancelUpload cancelled, detail: { file } (cancel button on the item)
oas-changeFile 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-cropCrop confirmed, detail: { file, blob } (file = original file, blob = offscreen canvas result)
oas-errorUpload 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-limitAdding 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-previewPreview overlay opened, detail: { file, url }
oas-progressUpload 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-removeFile removed, detail: { file, index }
oas-retryRetry clicked, detail: { file } (re-upload after failure)
oas-successUpload succeeded, detail: { file, response }
oas-uploadUpload progress, detail: { file, percent, status }

Slots ​

NameDescription
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)
triggerReplace the drop-zone content (zone semantics kept)

CSS Variables ​

CSS VariableDefault
--oas-upload-card-radiusvar(--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); ③ cloneNode does not carry event listeners — @click / addEventListener bound 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.

Released under the MIT OR Apache-2.0 License.