<c-file-upload>
A field the user adds files to by dropping them on it or choosing them from a file dialog — and, given an upload function, the place each file's upload shows its progress.
Usage
Value
The value is a list of file entries — always a list, even in a field that
takes one file. Each entry has an id, the file's name, size and
type, and a status:
status |
The entry |
|---|---|
local |
holds a file not yet sent — see Uploading later |
queued |
waits for a free upload slot — at most three run at once |
uploading |
is being sent |
done |
was sent, or is a file already on the server |
error |
failed; its error holds the text the row shows |
A file the user added carries the browser File as file; once uploaded,
result holds what the upload function resolved to. Bind the list with
v-model — an array, so it is a DOM property — or listen for change:
<c-file-upload v-model="files" label="Attachments" multiple />
The value events fire when the user adds, removes or retries a file, when
startUploads() starts files, and once when each upload finishes, done or
failed — never for progress, and never when value is set. Each event carries a new list of new entries.
Without multiple the field holds one file, and choosing another replaces
it.
Uploading
The field never sends a byte itself. Set upload to a function that sends
one file, and the field calls it for every added file as soon as it is
added:
picker.upload = (file, { onProgress, signal }) =>
new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => onProgress(e.loaded / e.total);
xhr.onload = () =>
xhr.status < 300
? resolve(JSON.parse(xhr.response))
: reject(new Error('The server refused the file'));
xhr.onerror = () => reject(new Error('Network error'));
signal.addEventListener('abort', () => xhr.abort());
xhr.open('POST', '/api/files');
xhr.send(file);
});
onProgress takes a fraction from 0 to 1; until its first call the row's
bar is indeterminate, so fetch — which reports no upload progress — works
too. The signal aborts when the user cancels, removes the entry, or the
field leaves the page. What the promise resolves to becomes the entry's
result, typically the server's id for the file.
When the promise rejects with an Error, its message is the text the row
shows, so throw the words the user should read — new Error('The file exceeds your quota'). Any other rejection, and the browser's own network
errors, show "Upload failed". Do not rethrow raw server responses.
A failed row offers a retry; a queued or uploading one, a cancel.
Uploading later
A manual field holds added files as local even with an upload function,
until startUploads() queues them — so a form can upload only when the user
asks:
<c-file-upload
ref="field"
v-model="files"
:upload="send"
label="Attachments"
manual
multiple
/>
<c-button @click="field?.startUploads()">Upload</c-button>
The call starts the files the field holds at that moment and fires the value
events once. Files added after it wait as local for the next call; a failed
row's retry still sends its file at once. Without an upload function the call
does nothing.
Without manual, there is no waiting: an upload function assigned later
queues every local entry at once, and so every file added after it.
Or leave upload unset and send the files with the rest of the form. Unlike
the other fields, a file upload takes no part in a native <form>
submission; build the FormData from the value:
const body = new FormData();
for (const entry of files) if (entry.file) body.append('files', entry.file);
Files already on the server
To show files the user uploaded earlier, set them as entries without a
file, with status: 'done' and the server's own id:
picker.value = [
{ id: 'f_12', name: 'contract.pdf', size: 120_400, status: 'done' },
];
Removing one only takes it out of the value. Deleting it on the server, if it should be, is the consumer's job — on submit, or by comparing the lists.
Keep each entry's id when the value passes through your own state: the
field matches entries by id, so a list rebuilt without it loses the
progress and the cancel of the files still uploading.
Accepted files
accept takes the native syntax — extensions and media types,
.pdf,image/*. It filters the file dialog, and the field checks a dropped
file against it too, since a drop bypasses the dialog. max-size caps a
file's size in bytes, and max-files the number of entries a multiple
field holds:
<c-file-upload
v-model="files"
accept=".pdf,image/*"
hint="PDF or images, up to 10 MB each"
label="Receipts"
max-files="5"
max-size="10000000"
multiple
/>
When the browser reports no media type for a file — Chrome on Windows does
for a .pptx when Office is not installed — the field takes it from the
extension. The entry's type, its file and the file the upload function
receives all carry that type, so a server that checks it gets the right one,
not application/octet-stream.
Sizes are shown in decimal units — 1 MB is 1,000,000 bytes, as on most
phones and Macs — so write max-size in decimal bytes. Name the accepted
types and limits in the hint; the field does not generate that text.
The field never holds the same file twice: a file already in the list —
picked again from the same folder, or matching a server file's name and
size — is refused too, and so is the one file of a field without multiple
when it is picked again.
A refused file never joins the value. It shows as a rejected row with the
reason, and the reject event lists every refused file with its reason:
type, size, duplicate, count or folder. The rows describe the
latest add, so the next change to the list — another add, a removal, or a
value set from outside — clears them, and the user can close each one.
Compact
compact shows the drop zone as a row at the shared control height — a
"Choose files" button and a drop prompt — so the field lines up with the
fields beside it. size="small" makes the row 36px tall:
<c-file-upload v-model="cv" compact label="CV" />
The file list sits under the drop zone in both layouts.
Dropping
The whole field takes a drop, not only the drop zone, so a drop that just
misses the zone still lands. While files are dragged over it, the zone
highlights and the host exposes the drag-over custom state.
Accessibility
Dragging is a pointer-only shortcut: the drop zone is a button that opens the file dialog, and on a touch screen its prompt reads "Choose files". Each row's buttons are named after the file — "Remove report.pdf", "Cancel upload of report.pdf". A polite announcement reports files added, each finished or failed upload and each rejected file; progress is never announced, but each uploading row's progress bar can be read on demand.
Texts
Every text the field shows or announces is in texts, merged over the
English defaults; set it per field or app-wide with applyDefaults. File
sizes follow the page's lang (1,2 Mt under lang="fi") and need no
texts.
Examples
<template>
<div>
<c-file-upload
v-model="files"
accept=".pdf,image/*"
hint="PDF or images, up to 10 MB each, at most 3"
label="Receipts"
max-files="3"
max-size="10000000"
multiple
@change="refused = ''"
@reject="refused = describe($event.detail)"
/>
<p>Refused: {{ refused || 'none' }}</p>
</div>
</template>
<script setup lang="ts">
import type { CFileUploadEntry, CFileUploadRejection } from '@cscfi/csc-ui';
import { ref } from 'vue';
const files = ref<CFileUploadEntry[]>([]);
// The latest add's refusals, cleared by the next change to the list — the
// `reject` event follows the `change` of the same add.
const refused = ref('');
const describe = (rejections: CFileUploadRejection[]): string =>
rejections.map(({ file, reason }) => `${file.name} (${reason})`).join(', ');
</script>
<template>
<div>
<c-file-upload
v-model="files"
hint="Any file, any size"
label="Attachments"
multiple
/>
<p>Files: {{ files.map((file) => file.name).join(', ') || 'none' }}</p>
</div>
</template>
<script setup lang="ts">
import type { CFileUploadEntry } from '@cscfi/csc-ui';
import { ref } from 'vue';
const files = ref<CFileUploadEntry[]>([]);
</script>
<template>
<div class="row">
<c-text-field v-model="name" label="Name" label-on-top />
<c-file-upload v-model="cv" accept=".pdf" hint="A PDF" label="CV" compact />
</div>
</template>
<script setup lang="ts">
import type { CFileUploadEntry } from '@cscfi/csc-ui';
import { ref } from 'vue';
const name = ref('');
const cv = ref<CFileUploadEntry[]>([]);
</script>
<style scoped>
.row {
display: grid;
gap: 16px;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
</style>
<template>
<div class="stack">
<c-file-upload
ref="field"
v-model="files"
:upload="send"
hint="Files wait until you press Upload"
label="Attachments"
manual
multiple
/>
<c-button :disabled="!waiting" @click="field?.startUploads()">
Upload
</c-button>
</div>
</template>
<script setup lang="ts">
import type {
CFileUploadElement,
CFileUploadEntry,
CFileUploadFunction,
} from '@cscfi/csc-ui';
import { computed, ref, useTemplateRef } from 'vue';
// Stands in for a real request: reports progress for two seconds, then
// resolves — or refuses a file whose name contains "fail".
const send: CFileUploadFunction = (file, { onProgress, signal }) =>
new Promise((resolve, reject) => {
let sent = 0;
const timer = setInterval(() => {
sent = Math.min(1, sent + 0.1);
onProgress(sent);
if (sent < 1) return;
clearInterval(timer);
if (file.name.includes('fail')) {
reject(new Error('The server refused the file'));
} else {
resolve({ id: `file-${Date.now()}` });
}
}, 200);
signal.addEventListener('abort', () => clearInterval(timer));
});
const field = useTemplateRef<CFileUploadElement>('field');
const files = ref<CFileUploadEntry[]>([]);
// A `manual` field holds added files as `local` until `startUploads()`.
const waiting = computed(() =>
files.value.some((file) => file.status === 'local'),
);
</script>
<style scoped>
.stack {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
</style>
<template>
<div>
<c-file-upload
v-model="files"
:upload
hint="Earlier uploads are listed; new files upload at once"
label="Project documents"
multiple
/>
<p>Documents: {{ files.map((file) => file.name).join(', ') || 'none' }}</p>
</div>
</template>
<script setup lang="ts">
import type { CFileUploadEntry, CFileUploadFunction } from '@cscfi/csc-ui';
import { ref } from 'vue';
// Stands in for a real request: reports progress for two seconds, then
// resolves — or refuses a file whose name contains "fail".
const upload: CFileUploadFunction = (file, { onProgress, signal }) =>
new Promise((resolve, reject) => {
let sent = 0;
const timer = setInterval(() => {
sent = Math.min(1, sent + 0.1);
onProgress(sent);
if (sent < 1) return;
clearInterval(timer);
if (file.name.includes('fail')) {
reject(new Error('The server refused the file'));
} else {
resolve({ id: `file-${Date.now()}` });
}
}, 200);
signal.addEventListener('abort', () => clearInterval(timer));
});
// Files uploaded earlier: no `file`, status `done`, the server's own id.
const serverFiles: CFileUploadEntry[] = [
{
id: 'f_12',
name: 'project-plan.pdf',
size: 482_113,
status: 'done',
type: 'application/pdf',
},
{
id: 'f_13',
name: 'budget.csv',
size: 92_400,
status: 'done',
type: 'text/csv',
},
];
const files = ref<CFileUploadEntry[]>(serverFiles);
</script>
<template>
<div>
<c-file-upload
v-model="files"
:texts
:upload
hint="Tiedosto, jonka nimi alkaa “fail”, hylätään"
label="Liitteet"
max-files="3"
multiple
/>
<p>Tiedostoja: {{ files.length }}</p>
</div>
</template>
<script setup lang="ts">
import type {
CFileUploadEntry,
CFileUploadFunction,
CFileUploadTexts,
} from '@cscfi/csc-ui';
import { ref } from 'vue';
// Every text, so none falls back to English.
const texts: CFileUploadTexts = {
announceAdded: (count) =>
count === 1 ? '1 tiedosto lisätty' : `${count} tiedostoa lisätty`,
announceFailed: (name, error) => `${name} epäonnistui: ${error}`,
announceRejected: (name, reason) => `${name}: ${reason}`,
announceUploaded: (name) => `${name} lähetetty`,
cancel: (name) => `Peruuta tiedoston ${name} lähetys`,
choose: (multiple) => (multiple ? 'valitse tiedostot' : 'valitse tiedosto'),
chooseButton: (multiple) =>
multiple ? 'Valitse tiedostot' : 'Valitse tiedosto',
close: (name) => `Sulje ${name}`,
compactPrompt: (multiple) =>
multiple ? 'tai pudota tiedostot tähän' : 'tai pudota tiedosto tähän',
dragPrompt: (multiple) =>
multiple ? 'Raahaa tiedostot tähän tai' : 'Raahaa tiedosto tähän tai',
dropActive: (multiple) =>
multiple
? 'Pudota tiedostot lisätäksesi ne'
: 'Pudota tiedosto lisätäksesi sen',
progress: (loaded, total, percent) => `${loaded} / ${total} · ${percent} %`,
queued: 'Jonossa',
rejectedCount: (max) =>
max === 1 ? 'Vain yksi tiedosto sallitaan' : `Enintään ${max} tiedostoa`,
rejectedDuplicate: 'Lisätty jo',
rejectedFolder: 'Kansioita ei tueta',
rejectedSize: (max) => `Suurempi kuin ${max}`,
rejectedType: 'Tiedostotyyppiä ei hyväksytä',
remove: (name) => `Poista ${name}`,
retry: (name) => `Yritä uudelleen: ${name}`,
uploaded: 'Lähetetty',
uploadFailed: 'Lähetys epäonnistui',
uploading: 'Lähetetään',
};
// Stands in for a real request: reports progress for two seconds, then
// resolves — or refuses a file whose name contains "fail".
const upload: CFileUploadFunction = (file, { onProgress, signal }) =>
new Promise((resolve, reject) => {
let sent = 0;
const timer = setInterval(() => {
sent = Math.min(1, sent + 0.1);
onProgress(sent);
if (sent < 1) return;
clearInterval(timer);
if (file.name.includes('fail')) {
reject(new Error('The server refused the file'));
} else {
resolve({ id: `file-${Date.now()}` });
}
}, 200);
signal.addEventListener('abort', () => clearInterval(timer));
});
const files = ref<CFileUploadEntry[]>([]);
</script>
<template>
<div>
<c-file-upload
v-model="files"
:upload
hint="A file named “fail…” is refused"
label="Datasets"
multiple
/>
<p>Uploaded: {{ done }} of {{ files.length }}</p>
</div>
</template>
<script setup lang="ts">
import type { CFileUploadEntry, CFileUploadFunction } from '@cscfi/csc-ui';
import { computed, ref } from 'vue';
// Stands in for a real request: reports progress for two seconds, then
// resolves — or refuses a file whose name contains "fail".
const upload: CFileUploadFunction = (file, { onProgress, signal }) =>
new Promise((resolve, reject) => {
let sent = 0;
const timer = setInterval(() => {
sent = Math.min(1, sent + 0.1);
onProgress(sent);
if (sent < 1) return;
clearInterval(timer);
if (file.name.includes('fail')) {
reject(new Error('The server refused the file'));
} else {
resolve({ id: `file-${Date.now()}` });
}
}, 200);
signal.addEventListener('abort', () => clearInterval(timer));
});
const files = ref<CFileUploadEntry[]>([]);
const done = computed(
() => files.value.filter((file) => file.status === 'done').length,
);
</script>
API reference
<c-file-upload>
A field the user adds files to by dropping them on it or choosing them from a file dialog — and, given an upload function, the place each file's upload shows its progress.
Properties
| Property | Attribute | Type | Default | Description |
|---|---|---|---|---|
accept | accept | string | '' | The file types the field takes, in the native `accept` syntax: extensions (`.pdf`) and media types (`image/*`, `application/json`), comma separated. It filters the file dialog and is checked again on a drop |
compact | compact | boolean | false app default | Show the drop zone as a control-height row — a "Choose files" button and a drop prompt — that lines up with the fields beside it |
disabled | disabled | boolean | false | Disable the field. Uploads already running continue |
errorMessage | error-message | string | '' | Error message shown in place of the hint while the field is invalid |
hideMessage | hide-message | boolean | false app default | Hide the message line — the hint and error messages under the field — and the room it keeps. |
hint | hint | string | '' | Hint text under the drop zone — the place to name the accepted types and limits |
invalid | invalid | boolean | false | Show the control as invalid: its `error-message`, when set, replaces the hint, and the control is marked `aria-invalid`. |
label | label | string | '' | Label of the field |
manual | manual | boolean | false | Hold added files as `local` even with an upload function, until `startUploads()` queues them — for a form that uploads on its own button. Files added after the call wait for the next one |
maxFiles | max-files | null | number | null | The most file entries a `multiple` field holds; files beyond it are rejected |
maxSize | max-size | null | number | null | The largest file in bytes; a larger one is rejected. Sizes are shown in decimal units, so write the limit in decimal bytes (`10000000` reads "10 MB") |
multiple | multiple | boolean | false | Let a pick or a drop add several files. Without it the field holds one file and a new pick replaces it; the value is a list either way |
required | required | boolean | false | Set the field as required |
size | size | CFieldSize | 'default' app default | Height of the `compact` row: the 52px default (the shared control height) or the 36px `small` row. The large drop zone has one size |
texts | — | | {} app default | UI text overrides (i18n), merged over the English defaults. Objects have no attribute form — bind as a DOM property |
upload | — | | — | The upload function: called once per added file with an abort signal and a progress callback taking a fraction from 0 to 1; what it resolves to becomes the entry's `result`, an `Error` it rejects with becomes the entry's `error` text. Without one the field only holds the files. A function — bind as a DOM property |
value | — | | null | The file entries — always a list. A picked file's entry carries the browser `File`; a server file's entry is `{ id, name, size, status: 'done' }`. `''` reads as empty — what a plain `v-model` holding `null` writes. An array — bind as a DOM property |
hideDetails deprecated | hide-details | boolean | false app default | Deprecated. Use `hide-message`. Hide the hint and error messages |
app default marks a prop you can set for every instance at once with applyDefaults() — an explicit attribute or property on an instance still wins.
Events
| Event | Detail | Description |
|---|---|---|
change | CFileUploadEntry[] | Fired with the new list of file entries. |
input | void | Native bubbling input event fired with every value change so a plain Vue `v-model` works. No detail. |
reject | CFileUploadRejection[] | Fired after an add that refused files, listing each with its reason — a type outside `accept`, a file over `max-size`, a file already held, one beyond `max-files`, or a folder. The refused files never join the value. |
update:value | CFileUploadEntry[] | v-model contract event, fired with `change`. |
Methods
| Method | Signature | Description |
|---|---|---|
focus | (options?: FocusOptions): void | Focus its drop zone's button, as `focus()` does on a native control: the element renders no box of its own to take it. |
startUploads | (): void | Queue every `local` file entry for the upload function — how a `manual` field starts; files added after the call wait for the next one. Fires the value events once when it starts any. Does nothing without an upload function |
CSS parts
Style from outside with c-file-upload::part(name) — parts are the library's only styling customization API.
| Part | Description |
|---|---|
root | The field: label, drop zone, message line and file list. The whole of it takes a drop |
label | The label above the drop zone |
drop-zone | The dashed drop zone — the large button, or the `compact` row |
message | The hint/error message area under the drop zone (always reserved unless `hide-message`) |
list | The list of file entries and rejected files |
entry | One file entry's row |
rejected | One rejected file's row |
progress | The progress track along an uploading row's bottom edge |
progress-bar | The bar inside it showing the row's upload progress, or its looping sweep while indeterminate |
Custom states
Select on the host's live state with c-file-upload:state(name) — combine with ::part() for per-state styling, e.g. c-file-upload:state(checked)::part(indicator) targets the indicator only while checked.
| State | Description |
|---|---|
drag-over | Present while files are dragged over the field |
Types
Importable from the package root: import type { … } from '@cscfi/csc-ui'
CFileUploadContext
The second argument of an upload function.
export interface CFileUploadContext {
/** The entry's id. */
id: string;
/** Report progress as a fraction from 0 to 1; the row stays indeterminate until the first call. */
onProgress: (fraction: number) => void;
/** Aborted when the user cancels, the entry is removed, or the field unmounts. */
signal: AbortSignal;
}CFileUploadEntry
One file a `c-file-upload` holds (CONTEXT.md "File entry").
export interface CFileUploadEntry {
/** The rejection text shown for a failed upload. */
error?: string;
/** The browser file, for a file the user added, typed as `type` says. Absent on a server file. */
file?: File;
/** Stable identity: generated for an added file, the consumer's own for a server file. */
id: string;
/** The file name. */
name: string;
/** What the upload function resolved to. */
result?: unknown;
/** The size in bytes. */
size: number;
/** Where the entry stands. */
status: CFileUploadStatus;
/** The media type: the browser's, or the one its extension implies when the browser reports none. */
type?: string;
}CFileUploadFunction
Sends one file; resolves to the entry's `result` or rejects to mark it failed.
export type CFileUploadFunction = (
file: File,
context: CFileUploadContext,
) => Promise<unknown>;CFileUploadRejection
One rejected file, as the `reject` event reports it.
export interface CFileUploadRejection {
/** The refused file, as the browser handed it. */
file: File;
/** Why it was refused. */
reason: CFileUploadRejectReason;
}CFileUploadRejectReason
Why a file was rejected.
export type CFileUploadRejectReason =
| 'count'
| 'duplicate'
| 'folder'
| 'size'
| 'type';CFileUploadStatus
Where a file entry stands (CONTEXT.md "Upload status").
export type CFileUploadStatus =
| 'done'
| 'error'
| 'local'
| 'queued'
| 'uploading';CFileUploadTexts
UI texts of `c-file-upload`, merged key by key over the English defaults.
export interface CFileUploadTexts {
/** Announced after an add, with the number of files added. */
announceAdded?: (count: number) => string;
/** Announced when an upload fails, with the file name and the row's error text. */
announceFailed?: (name: string, error: string) => string;
/** Announced for a rejected file, with its name and the reason text. */
announceRejected?: (name: string, reason: string) => string;
/** Announced when an upload is done, with the file name. */
announceUploaded?: (name: string) => string;
/** Accessible label of a queued or uploading row's cancel button. */
cancel?: (name: string) => string;
/** The link-styled end of the large drop zone's prompt. */
choose?: (multiple: boolean) => string;
/** The compact row's button, and the large drop zone's prompt on a touch screen. */
chooseButton?: (multiple: boolean) => string;
/** Accessible label of a rejected row's close button. */
close?: (name: string) => string;
/** The compact row's prompt beside its button. */
compactPrompt?: (multiple: boolean) => string;
/** The large drop zone's prompt before the choose link. */
dragPrompt?: (multiple: boolean) => string;
/** The drop zone's prompt while files are dragged over the field. */
dropActive?: (multiple: boolean) => string;
/** An uploading row's status: bytes sent, file size (both formatted) and the whole percentage. */
progress?: (loaded: string, total: string, percent: number) => string;
/** A queued row's status. */
queued?: string;
/** Rejection reason: a file beyond the count the field holds. */
rejectedCount?: (max: number) => string;
/** Rejection reason: a file the field already holds. */
rejectedDuplicate?: string;
/** Rejection reason: a dropped folder. */
rejectedFolder?: string;
/** Rejection reason: a file over `max-size`, with the formatted limit. */
rejectedSize?: (max: string) => string;
/** Rejection reason: a type outside `accept`. */
rejectedType?: string;
/** Accessible label of a row's remove button. */
remove?: (name: string) => string;
/** Accessible label of a failed row's retry button. */
retry?: (name: string) => string;
/** Accessible name of a done row's check mark. */
uploaded?: string;
/** A failed row's status when the upload function gave no message. */
uploadFailed?: string;
/** An uploading row's status before the first progress report. */
uploading?: string;
}CFieldSize shared
Field height of the form controls built on `c-input`. `default` is the 44px field; `small` is the 36px field. Owned here because the value passes from the wrapping control (`c-select`) into `c-input`.
export type CFieldSize = 'default' | 'small';