Upload / UploadDragger
Select, drag and drop files with a controlled list.
When to use
Upload selects files and shows the upload progress, result and available actions. UploadDragger adds a drag area with the same list and transport contract. Use them for attachments, avatars, and image sets.
Demos process files locally: customRequest simulates sending, and manual script defers it until the button is clicked. For your application, specify a server action or your own request implementation.
CSS prefixes Upload show global ConfigProvider.prefixCls and local prefixCls without resetting state. Trigger, list and Upload/Dragger states follow prefixCls. Button, Progress and Tooltip separately inherit the common prefix. Here is manual mode: file selection does not send a network request.
List and pre-processing
FileList - an UploadFile array with a stable uid, name, state and progress. When controlling externally, accept info.fileList from each onChange. defaultFileList specifies initial entries, such as previously saved attachments.
| Problem | Setting | Example |
|---|---|---|
| Select and send files | customRequest, onChange |
Click to download |
| Manage list and deletion | fileList, onRemove |
Managed List |
| Set file error text | response, error.statusText, error.message, locale.uploadError |
Initial list |
| Select folder with attachments | directory, accept |
Folder and attachments |
| Customize name link | UploadFile.linkProps |
Link attributes |
| Set defaults to everyone Upload | ConfigProvider.upload | General settings |
| Customize action icons | showUploadList.*Icon |
Icons and information |
| Configure loading bar | progress, UploadFile.percent |
Progress registration |
Design parts of the list and trigger |
classNames, styles |
Semantic DOM |
| Change file icon | snippet iconRender |
Your icons |
| Rearrange files and change line | itemRender, fileList |
Own line and order |
| Receive files from buffer | pastable, beforeUpload |
Inserting files |
| Exclude inappropriate file | beforeUpload, UPLOAD_LIST_IGNORE |
PNG only |
| Change the body before sending | Returned Blob | Transformation before request |
| Delay sending | beforeUpload={() => false} |
Manual download start |
beforeUpload=false stops automatic uploading, but leaves the file in the list without the required status. A rejected Promise also stops the request. The separately imported constant UPLOAD_LIST_IGNORE eliminates the entry completely. The Blob returned by the handler replaces the body of the request; the source file is saved in the model.
pastable enables pasting files from the buffer for Upload and UploadDragger; default is false. The handler listens to the entire document: focus on an adjacent field does not limit loading. A regular text insert remains native. Each active Upload with pastable receives an event, so on a page with several loaders, enable it only for the one you need. disabled, including ConfigProvider, blocks insertion. When leaving the page, the subscription is removed.
Inserted files go through the same beforeUpload, fileList-driven transport that select and drop do. With multiple paste/drop, filters by accept; in single the first source file is taken before filtering. Check mandatory restrictions separately in beforeUpload. Example starts with insertion disabled, saves files locally and allows you to switch to Dragger or local customRequest without a network.
directory adds directory/webkitdirectory to file input. The dialog selects a folder, drop/paste bypasses the nested FileSystemEntry and saves the relative path to originFileObj.webkitRelativePath. Traversal reads all portions directory reader; unavailable entries are skipped. multiple remains a separate prop and does not limit the traversal to a single file. When disabled or leaving the page, the late reading result is not included in the list.
With directory accept is applied before beforeUpload, including selection by dialog. An object with filter:'native' leaves the checking to the browser; callback filter sets its own check. Support for selecting folders and entries when drop/paste is browser dependent: if entries are not available, crawling does not restore them from regular files. The structure on the server is determined by your transport, not the fileList.
accept specifies the available selection formats; beforeUpload is suitable for checking size and application conditions. multiple allows multiple files, maxCount limits the list; if maxCount=1, the new file replaces the old one. An entry removed from a managed model no longer receives status updates: keep the list up-to-date for late transport responses.
Request, progress and cancellation
Standard sending uses XHR: action specifies the URL, name is the name of the file field, method is the HTTP method. data, headers and withCredentials pass the request parameters. action and data can be calculated asynchronously for a specific file.
customRequest receives file, action, filename, method, data, headers and callbacks onProgress/onSuccess/onError. Report the percentage via onProgress and terminate the request with one of the last two handlers. info.defaultRequest allows you to call the original XHR implementation instead of completely repeating the transport.
Return an object with an abort() method from customRequest. Use it to stop the request and release its resources. When Upload unmounts, it calls this method for each pending upload, even if customRequest closed the form before returning the object.
To cancel an upload from a button, get the Upload instance with bind:this. Call abort(file) for one request or abort() for all active requests. In the basic example, the button also updates the status of the cancelled files in the controlled fileList.
onRemove can return false or a Promise with false to prevent removal; a rejected Promise also saves the record. If deletion is allowed, the active send is cancelled. Guided Example shows delete prohibited separately from disabled.
List view and actions
listType selects text, picture, picture-card or picture-circle. Wall of images and round version use the same model. Url specifies the file link, thumbUrl specifies the thumbnail; previewFile allows you to asynchronously prepare your image.
linkProps sets the attributes of the file name link if there is a url: an HTMLAnchorAttributes object or JSON. Native class, onclick and string style are used. target, rel, title, download, aria-* and data-* can be specified explicitly; href is always taken from file.url. Attributes do not apply to a thumbnail, a separate preview action, or a name without a url.
onclick is called before onPreview. event.preventDefault() cancels preview, return false and stopPropagation() do not. JSON only transfers serializable attributes; an invalid line throws a SyntaxError. In the example, you can disable onPreview and download local text via download.
showUploadList configures the visibility of preview/remove/download and snippet extra. Snippets previewIcon/downloadIcon/removeIcon receive the file and change the contents of regular actions. ShowIcon, names from locale, statuses, disabled and callbacks are preserved. Preview icon is used in card/circle, download - only for done. An empty snippet does not hide the control: to do this, set showIcon; undefined returns standard SVG, 0 is displayed. onPreview and onDownload pass the action to the application: demos open the local Modal or show the file name. Free Object URLs created by the application when replacing or deleting an image and when unmounting.
children sets the Svelte snippet of the Dragger button or content. Pass disabled to the child button too, so that its appearance and accessibility are consistent with Upload. bind:inputElement and bind:nativeElement are available after mount; There are no separate focus/blur.
iconRender - Svelte snippet with file and current listType. It replaces the icon, including the uploading state. An empty snippet leaves space without a fallback; the number 0 is displayed. The finished image thumbnail in picture views remains a priority.
itemRender gets originNode, file, current readonly fileList and actions. originNode is rendered via @render originNode() and includes the standard error Tooltip line. You can supplement it or replace it completely. An empty snippet leaves the outer file container empty; undefined returns the default string.
The UploadItemRenderActions type describes preview(event?), download() and remove(). They call callbacks Upload; remove saves veto onRemove and canceling the request. The passed preview MouseEvent is canceled if onPreview is present; without a callback, the action does not open the viewer automatically. Custom buttons do not inherit the disabled and visibility of actions: set them explicitly. In the download example, it only shows the file name.
The order is determined by the fileList array of the application. The example combines native drag and drop with accessible Above/Below buttons; the stable uid is saved by the note editor. itemRender itself does not sort the data and does not include React dnd-kit.
Progress configures the linear file bar: size, showInfo, colors/gradient, status/success, steps, format, semantic slots and ARIA of an existing Progress. type and percent are not included in the object: the percentage is stored in UploadFile and updated by the transport via onProgress. For thickness use size. The bar appears 300 ms after the mount line, only when uploading and percent is specified; with SSR it doesn’t exist yet.
Without local and general progress, size=[-1,2] and showInfo=false are used. Global and local parameters are combined by field: a local empty object stores provider progress. If there is no general progress, the passed object, including the empty one, replaces defaults Upload; missing fields receive defaults Progress. The available name can be set using the aria-label/aria-labelledby fields of UploadFile; progress props take precedence. If a name is not specified, localized text is stored with the file name.
classNames/styles is styled as root, list, item and trigger. classNames specifies classes, styles – CSS strings; both accept record or callback from { props }. Callback sees listType, type, multiple, hasControlInside, disabled and showUploadList enabled, other input settings remain original. DOM bindings nativeElement/inputElement are not passed to callback. Don't change the state inside the callback.
Root - external wrapper span, list - list container, item - regular line inside the file container, trigger - selection area or Dragger, not hidden input. If itemRender completely replaces originNode, the item slot is not rendered. class and rootClassName complement classNames.root; styles.root is applied to the wrapper and its variables. Regular style refers to trigger and overrides styles.trigger. Progress settings have their own semantic slots.
ConfigProvider.upload specifies class/style, classNames/styles, accept, customRequest and progress for Upload and Dragger. A nested provider without upload inherits record; the transmitted upload replaces it entirely. An empty object clears only the upload-record, not the theme and other settings.
Classes from the general and local design are accumulated. The CSS lines for general slots come before local ones; for trigger the order is: general styles.trigger, general style, local styles.trigger, local style. Local empty classNames/styles do not override global ones. Callback receives the original local accept, not the inherited value. An empty local accept removes the general filter; checking the validity of the file remains a beforeUpload task.
Local customRequest has priority over the general one. Changing the handler affects the following files, the running request and the list are saved. The example holds requests until the button is pressed and shows the cancellation of incomplete ones with unmount; in an area with an empty record beforeUpload returns false so as not to run the standard XHR.
Component Upload design tokens work and are set separately from component config. Supported settings are listed in API.
Refs and file metadata
Lifecycle methods demonstrate UploadRef for Upload and UploadDragger through bind:this. onBatchStart accepts UploadBatchFileInfo[] containing file and parsedFile: null retains the file without uploading. It does not run beforeUpload or a transport. onProgress, onSuccess and onError update a record only while its uid remains in the current list; onSuccess parses a JSON response string.
FileList, upload, nativeElement and inputElement are read from the current ref. UploadUploaderRef provides abort(file?), which cancels a request without removing its row. After unmount, batch preparation neither publishes records nor starts a transport.
In the picture wall, fileName stores optional metadata and the application uses preview as a cache. The row label still uses name; thumbnails use thumbUrl/url. children=undefined hides the selection area at the limit while preserving the hidden input for the next selection.
Examples
The model is updated immediately; the deleted line remains until the end of the animation. Returning the same uid before completion saves the string. The initial files appear without animation; The system motion reduction setting is taken into account.
Adding and deleting rows
Four types of list, returning the same uid and disabling motion. The model list changes immediately, registration is completed separately.
<script lang="ts">
import {
Button,
Checkbox,
ConfigProvider,
Upload,
type UploadFile,
type UploadProps
} from '@woodger/antd';
let listType = $state<NonNullable<UploadProps['listType']>>('text');
let motion = $state(true);
let showTrigger = $state(true);
let nextId = 1;
const initial: UploadFile = {
uid: 'initial',
name: 'logo.webp',
status: 'done',
url: '/logo.webp'
};
let files = $state.raw<UploadFile[]>([initial]);
</script>
<p><label>{("List view ")}<select bind:value={listType}>
<option value="text">text</option><option value="picture">picture</option>
<option
value="picture-card"
>picture-card</option><option
value="picture-circle"
>picture-circle</option>
</select></label></p>
<p><Checkbox bind:checked={showTrigger}>{("Show selection area")}</Checkbox></p>
<p><Checkbox bind:checked={motion}>{("List animations")}</Checkbox></p>
<p>
<Button onclick={() => {
const id = nextId++; files = [...files, {
...initial,
uid: `added-${id}`,
name: `logo-${id}.webp`
}];
}}>{("Add ready file")}</Button>
<Button onclick={() => { files = files.filter(file => file.uid !== initial.uid); }}>
{("Remove source file")}
</Button>
<Button onclick={() => {
if (!files.some(file => file.uid === initial.uid)) {
files = [initial, ...files];
}
}}>{("Return original file")}</Button>
</p>
{#snippet trigger()}<Button>{("Choose a file for animation")}</Button>{/snippet}
<ConfigProvider theme={{ token: { motion } }}>
<Upload {listType} fileList={(files)} prefixCls="example-upload-motion"
beforeUpload={() => false} hasControlInside children={showTrigger ? trigger : undefined}
onChange={info => { files = info.fileList; }} />
</ConfigProvider>
<p><output aria-label={("Model files")}>{(files.map(file => file.name).join(', ')
|| ("Empty list"))}</output></p>
<p>
{("The model is updated immediately; the deleted line remains until the end of the animation. Returning the same uid before completion saves the string. The initial files appear without animation; The system motion reduction setting is taken into account.")}
</p>
Empty thumbUrl saves the image and preview by url, but disables the generation of previewFile. The generator needs originFileObj and thumbUrl === undefined. A non-empty thumbUrl takes precedence.
Thumbnail and preview source
Empty thumbUrl uses url without generation; non-empty takes precedence. If undefined and originFileObj is used, previewFile is called.
<script lang="ts">
import { onMount } from 'svelte';
import { Modal, Upload, type UploadFile, type UploadProps } from '@woodger/antd';
let listType = $state<NonNullable<UploadProps['listType']>>('picture');
let mode = $state('empty');
let origin = $state<UploadFile['originFileObj']>();
let calls = $state(0);
let preview = $state('');
const url = '/logo.webp';
const thumbnail = 'data:image/svg+xml,'
+ encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="80"><rect width="120" height="80" fill="#722ed1"/></svg>');
let file = $derived<UploadFile>({
uid: 'thumbnail', name: 'logo.webp', status: 'done', url,
thumbUrl: mode === 'empty'
? ''
: mode === 'custom'
? thumbnail
: undefined,
originFileObj: origin
});
onMount(() => {
origin = Object.assign(new File(['local preview'], 'logo.webp', { type: 'image/webp' }), {
uid: 'thumbnail'
});
});
</script>
<style>
select { max-inline-size: 100%; }
</style>
<p><label>{("Thumbnail view ")}<select bind:value={listType}>
<option
value="picture"
>picture</option><option
value="picture-card"
>picture-card</option><option
value="picture-circle"
>picture-circle</option>
</select></label></p>
<p><label>{("Thumbnail source ")}<select bind:value={mode}>
<option value="empty">{("Empty thumbUrl: use url")}</option>
<option value="custom">{("Non-empty thumbUrl: own thumbnail")}</option>
<option value="generated">{("thumbUrl not set: call previewFile")}</option>
</select></label></p>
<Upload {listType} fileList={([file])} showUploadList={({
showRemoveIcon: false
})}
previewFile={async () => {
calls++;
return thumbnail;
}}
onPreview={current => { preview = current.thumbUrl || current.url || ''; }} />
<p><output aria-label={("Calls previewFile")}>{calls}</output></p>
<p>
{("Empty thumbUrl saves the image and preview by url, but disables the generation of previewFile. The generator needs originFileObj and thumbUrl === undefined. A non-empty thumbUrl takes precedence.")}
</p>
<Modal
open={Boolean(preview)}
title={("Preview source")}
footer={null}
onCancel={() => { preview = ''; }}
>
{#if preview}<img
src={preview}
alt={("Selected source")}
style="
display: block;
max-width: 100%;
margin: auto;
"
/>{/if}
</Modal>
Push to load
Local customRequest shows progress and completion. A name ending in .fail shows an error. Removing or aborting cancels the timers; requests to the server are not fulfilled.
<script lang="ts">
import { Button, Upload, type UploadFile, type UploadRequestOptions } from '@woodger/antd';
let control = $state<InstanceType<typeof Upload>>();
let files = $state.raw<UploadFile[]>([]);
function request(options: UploadRequestOptions) {
const progress = setTimeout(() => {
options.onProgress?.({ percent: 50 });
}, 350);
const completion = setTimeout(() => {
if (options.file.name.endsWith('.fail')) {
options.onError?.(new Error(("Demo boot error")));
}
else {
options.onSuccess?.({ demo: true });
}
}, 800);
return {
abort() {
clearTimeout(progress);
clearTimeout(completion);
}
};
}
function handleAbort() {
control?.abort();
files = files.map(file => file.status === 'uploading'
? { ...file, status: 'error', error: new Error(("Loading cancelled.")) }
: file);
}
</script>
<style>
output { overflow-wrap: anywhere; }
</style>
<Upload
bind:this={control}
fileList={(files)}
multiple
customRequest={request}
onChange={info => { files = info.fileList; }}
>
<Button>{("Select files")}</Button>
</Upload>
<p><Button
disabled={!files.some(file => file.status === 'uploading')}
onclick={handleAbort}
>{("Cancel requests")}</Button></p>
<p><output aria-label={("Download status")}>{(files.map(
file => `${file.name}: ${file.status ?? 'pending'} (${file.percent ?? 0}%)`
).join('; ') || ("No files selected"))}</output></p>
Avatar selection
beforeUpload checks PNG/JPEG up to 1 MB. false stops sending, keeping the local preview. Object URL is freed when replaced and unmounted.
<script lang="ts">
import { onDestroy } from 'svelte';
import { Upload, UPLOAD_LIST_IGNORE, type UploadRcFile } from '@woodger/antd';
let image = $state('');
let name = $state('');
let error = $state('');
function handleFile(file: UploadRcFile) {
if (!['image/png', 'image/jpeg'].includes(file.type) || file.size > 1024 * 1024) {
error = ("Select PNG or JPEG up to 1 MB in size.");
return UPLOAD_LIST_IGNORE;
}
if (image) URL.revokeObjectURL(image);
image = URL.createObjectURL(file);
name = file.name;
error = '';
return false;
}
onDestroy(() => {
if (image) URL.revokeObjectURL(image);
});
</script>
<style>
.avatar {
display: grid;
place-items: center;
width: 104px;
height: 104px;
padding: 0;
overflow: hidden;
border: 1px dashed var(--ant-color-border);
border-radius: 50%;
background: var(--ant-color-fill-quaternary);
color: var(--ant-color-text);
cursor: pointer;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
<Upload
accept="image/png,image/jpeg"
maxCount={1}
showUploadList={(false)}
beforeUpload={handleFile}
>
<button class="avatar" type="button" aria-label={("Select avatar")}>
{#if image}
<img src={image} alt={("Selected avatar")} />
{:else}
<span>
{("+ Avatar")}
</span>
{/if}
</button>
</Upload>
<p><output aria-label={("Avatar file")}>{((error || name)
|| ("Avatar not selected"))}</output></p>
Initial file list
defaultFileList specifies the ready states done, uploading and error. Point to archive.zip: error.statusText takes precedence over error.message. beforeUpload=false allows you to add files without automatic upload.
<script lang="ts">
import { Button, Upload, type UploadFile } from '@woodger/antd';
const initial: UploadFile[] = [
{ uid: 'ready', name: 'readme.txt', status: 'done' },
{ uid: 'pending', name: 'draft.txt', status: 'uploading', percent: 40 },
{
uid: 'failed',
name: 'archive.zip',
status: 'error',
error: { statusText: "Server rejected archive", message: "Failed to load" }
}
];
</script>
<Upload defaultFileList={(initial)} beforeUpload={() => false}>
<Button>{("Add to start list")}</Button>
</Upload>
Wall of images
Managed picture-card with local thumbnails, deletion and Modal. Preview also works for added files; Object URLs are cleared.
<script lang="ts">
import { onDestroy } from 'svelte';
import {
Modal,
Upload,
UPLOAD_LIST_IGNORE,
type UploadChangeParam,
type UploadFile,
type UploadRcFile
} from '@woodger/antd';
const thumbnail = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="160" height="120" viewBox="0 0 160 120"><rect width="160" height="120" fill="#f9f0ff"/><rect x="24" y="24" width="112" height="72" rx="12" fill="#722ed1"/><circle cx="80" cy="60" r="20" fill="#fff"/></svg>'
);
let files = $state.raw<UploadFile[]>([{
uid: 'cover',
name: 'cover.svg',
fileName: 'cover-original.svg',
preview: thumbnail,
status: 'done',
url: thumbnail,
thumbUrl: thumbnail
}]);
let preview = $state('');
const urls = new Map<string, string>();
function handleFile(file: UploadRcFile) {
if (!file.type.startsWith('image/')) {
return UPLOAD_LIST_IGNORE;
}
return false;
}
function handleChange(info: UploadChangeParam) {
const retained = new Set(info.fileList.map(file => file.uid));
for (const [uid, url] of urls) {
if (retained.has(uid)) {
continue;
}
if (preview === url) preview = '';
URL.revokeObjectURL(url);
urls.delete(uid);
}
files = info.fileList.map(file => {
let url = urls.get(file.uid);
if (!url && file.originFileObj) {
url = URL.createObjectURL(file.originFileObj);
urls.set(file.uid, url);
}
return {
...file,
url: url ?? file.url,
thumbUrl: url ?? file.thumbUrl,
preview: url ?? file.preview
};
});
}
function handleRemove(file: UploadFile) {
const url = urls.get(file.uid);
if (!url) {
return;
}
if (preview === url) preview = '';
URL.revokeObjectURL(url);
urls.delete(file.uid);
}
onDestroy(() => {
for (const url of urls.values()) URL.revokeObjectURL(url);
});
</script>
<style>
.add {
display: grid;
place-content: center;
gap: 4px;
width: 100%;
height: 100%;
border: 0;
background: transparent;
color: inherit;
font: inherit;
cursor: pointer;
}
.preview {
display: block;
max-width: 100%;
max-height: 60vh;
margin: auto;
object-fit: contain;
}
</style>
<Upload
fileList={(files)}
accept="image/*"
listType="picture-card"
multiple
maxCount={3}
beforeUpload={handleFile}
onChange={handleChange}
onRemove={handleRemove}
children={files.length < 3 ? addButton : undefined}
onPreview={file => { preview = file.preview ?? file.url ?? file.thumbUrl ?? ''; }}
/>
{#snippet addButton()}
<button class="add" type="button" aria-label={("Add image")}><span aria-hidden="true">+</span>{("Add")}</button>
{/snippet}
<Modal
open={Boolean(preview)}
title={("Image preview")}
footer={null}
onCancel={() => { preview = ''; }}
>
{#if preview}<img
class="preview"
src={preview}
alt={("Selected image")}
/>{/if}
</Modal>
Round images
listType="picture-circle" changes the shape of the thumbnails. The file selection remains local thanks to beforeUpload=false.
<script lang="ts">
import { onDestroy } from 'svelte';
import { Modal, Upload, type UploadFile } from '@woodger/antd';
const thumbnail = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="160" height="120" viewBox="0 0 160 120"><rect width="160" height="120" fill="#f9f0ff"/><rect x="24" y="24" width="112" height="72" rx="12" fill="#722ed1"/><circle cx="80" cy="60" r="20" fill="#fff"/></svg>'
);
const initial: UploadFile[] = [{
uid: 'circle',
name: 'circle.svg',
status: 'done',
thumbUrl: thumbnail
}];
let preview = $state('');
let ownedPreview: string | undefined;
function closePreview() {
if (ownedPreview) URL.revokeObjectURL(ownedPreview);
ownedPreview = undefined;
preview = '';
}
function showPreview(file: UploadFile) {
closePreview();
preview = file.url ?? file.thumbUrl ?? '';
if (!preview && file.originFileObj) {
ownedPreview = URL.createObjectURL(file.originFileObj);
preview = ownedPreview;
}
}
onDestroy(closePreview);
</script>
<style>
.add {
width: 100%;
height: 100%;
border: 0;
background: transparent;
color: inherit;
font-size: 24px;
cursor: pointer;
}
.preview {
display: block;
max-width: 100%;
max-height: 60vh;
margin: auto;
}
</style>
<Upload
onPreview={showPreview}
defaultFileList={(initial)}
listType="picture-circle"
accept="image/*"
beforeUpload={() => false}
>
<button
class="add"
type="button"
aria-label={("Add a round image")}
>+</button>
</Upload>
<Modal
open={Boolean(preview)}
title={("File preview")}
footer={null}
onCancel={closePreview}
>
{#if preview}<img
class="preview"
src={preview}
alt={("Image preview")}
/>{/if}
</Modal>
Managed list and deletion veto
fileList belongs to the application. onRemove can reject the removal; the outer Button shows a separate model change.
<script lang="ts">
import { Button, Upload, type UploadFile } from '@woodger/antd';
let files = $state.raw<UploadFile[]>([
{ uid: 'keep', name: 'policy.txt', status: 'done' },
{ uid: 'draft', name: 'draft.txt', status: 'done' }
]);
let canRemove = $state(false);
</script>
<p>
<label><input type="checkbox" bind:checked={canRemove} />{(" Allow policy deletion")}</label>
</p>
<Upload fileList={(files)} beforeUpload={() => false} onChange={info => {
files = info.fileList;
}}
onRemove={file => file.uid !== 'keep' || canRemove}>
<Button>{("Add document")}</Button>
</Upload>
<p>
<Button onclick={() => { files = files.filter(file => file.uid !== 'draft'); }}>
{("Remove draft")}
</Button>
</p>
<p><output aria-label={("Managed files")}>{(files.map(file => file.name).join(', ')
|| ("Empty list"))}</output></p>
Click or drag files
The files will remain in the local list.
Drag and drop files
UploadDragger accepts files through file selection and the drop event. onDrop receives event; beforeUpload=false saves files locally.
<script lang="ts">
import { UploadDragger, type UploadFile } from '@woodger/antd';
let files = $state.raw<UploadFile[]>([]);
let dropped = $state(0);
</script>
<UploadDragger fileList={(files)} multiple beforeUpload={() => false}
onDrop={event => { dropped = event.dataTransfer?.files.length ?? 0; }}
onChange={info => { files = info.fileList; }}>
<p class="ant-upload-text">{("Click or drag files")}</p>
<p class="ant-upload-hint">{("The files will remain in the local list.")}</p>
</UploadDragger>
<p><output
aria-label={("Result drop")}
>Drop: {dropped}{("; files: ")}{(files.length)}</output></p>
PNG only
accept limits the selection in the dialog, beforeUpload checks the type. UPLOAD_LIST_IGNORE excludes a rejected file from the list; false keeps valid without sending.
<script lang="ts">
import {
Button,
Upload,
UPLOAD_LIST_IGNORE,
type UploadFile,
type UploadRcFile
} from '@woodger/antd';
let files = $state.raw<UploadFile[]>([]);
let message = $state('');
function validate(file: UploadRcFile) {
if (file.type !== 'image/png') {
message = ("This file is not a PNG.");
return UPLOAD_LIST_IGNORE;
}
message = ("PNG accepted without sending.");
return false;
}
</script>
<Upload
fileList={(files)}
accept="image/png"
beforeUpload={validate}
onChange={info => { files = info.fileList; }}
>
<Button>{("Select PNG")}</Button>
</Upload>
<p><output aria-label={("Check PNG")}>{(message
|| ("Select PNG file"))}</output></p>
<p><output aria-label={("Accepted PNG")}>{(files.map(file => file.name).join(', ')
|| ("List is empty"))}</output></p>
Turn on paste, copy the file or image and press Ctrl+V or ⌘V. The handler acts on the entire document, including when there is focus in the note field below. Plain text continues to be inserted into the field.
By default, beforeUpload=false leaves files locally. If you clear this flag, customRequest only confirms the local result, without a network request. Multiple uses accept; in single paste/drop takes the first source file before filtering. Specify file validity check separately in beforeUpload.
Inserting files from the buffer
pastable for Upload and UploadDragger: paste document processing, multiple/accept, beforeUpload, local customRequest and disabled. Insertion is enabled explicitly; files are not sent to the server.
<script lang="ts">
import {
Button, Checkbox, ConfigProvider, TextArea, Upload, UploadDragger,
type UploadFile, type UploadProps
} from '@woodger/antd';
let enabled = $state(false);
let localDisabled = $state(false);
let providerDisabled = $state(false);
let dragger = $state(false);
let multiple = $state(true);
let textOnly = $state(false);
let manual = $state(true);
let files = $state.raw<UploadFile[]>([]);
let checked = $state<string[]>([]);
let batches = $state<string[]>([]);
let requests = $state<string[]>([]);
let changes = $state(0);
let draft = $state(("Note next to download"));
let root = $state<HTMLSpanElement>();
let input = $state<HTMLInputElement>();
const props = $derived<UploadProps>({
pastable: enabled,
disabled: localDisabled ? true : undefined,
multiple,
accept: textOnly ? '.txt' : undefined,
fileList: files,
beforeUpload: (file, batch) => {
checked.push(`${file.name} (${file.type || "without type"})`);
batches.push(batch.map(item => item.name).join(', '));
return manual ? false : undefined;
},
onChange: info => {
files = info.fileList;
changes++;
},
customRequest: options => {
requests.push(options.file.name);
let cancelled = false;
queueMicrotask(() => {
if (!cancelled) options.onSuccess?.({ local: true });
});
return { abort() { cancelled = true; } };
}
});
</script>
<style>
.example {
display: grid;
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={enabled}>{("Enable file insertion")}</Checkbox>
<Checkbox bind:checked={dragger}>{("Insertion via UploadDragger")}</Checkbox>
<Checkbox bind:checked={multiple}>{("Several files from the buffer")}</Checkbox>
<Checkbox bind:checked={textOnly}>{("Accept .txt when inserting")}</Checkbox>
<Checkbox
bind:checked={manual}
>{("Leave inserted files without sending")}</Checkbox>
<Checkbox
bind:checked={localDisabled}
>{("Block insert locally")}</Checkbox>
<Checkbox
bind:checked={providerDisabled}
>{("Block insertion via provider")}</Checkbox>
</div>
<p>
{("Turn on paste, copy the file or image and press Ctrl+V or ⌘V. The handler acts on the entire document, including when there is focus in the note field below. Plain text continues to be inserted into the field.")}
</p>
<TextArea
aria-label={("Note next to file insertion")}
bind:value={draft}
rows={3}
/>
<ConfigProvider componentDisabled={providerDisabled}>
{#if dragger}
<UploadDragger {...props} bind:nativeElement={root} bind:inputElement={input}>
<p>{("Click, drag, or paste files from the clipboard")}</p>
</UploadDragger>
{:else}
<Upload {...props} bind:nativeElement={root} bind:inputElement={input}>
<Button disabled={localDisabled ? true : undefined}>
{("Select files to insert")}
</Button>
</Upload>
{/if}
</ConfigProvider>
<output aria-label={("List of inserted files")}>
{(files.map(file => `${file.name}: ${file.status ?? "without sending"}`).join('; ')
|| ("Empty"))}
</output>
<output aria-label={("Checking inserted files")}>{(checked.join('; ')
|| ("No checks"))}</output>
<output aria-label={("Batches of inserted files")}>{(batches.join(' | ')
|| ("No batches"))}</output>
<output aria-label={("Local insert queries")}>{(requests.join(', ')
|| ("No requests"))}</output>
<output
aria-label={("Insert List Events")}
>{("Changes: ")}{changes}</output>
<output aria-label={("Roots of insertion Upload")}>{(root && input ? "Connected" : "Waiting mount")}</output>
<p>
{("By default, beforeUpload=false leaves files locally. If you clear this flag, customRequest only confirms the local result, without a network request. Multiple uses accept; in single paste/drop takes the first source file before filtering. Specify file validity check separately in beforeUpload.")}
</p>
</div>
Click or drag a folder with text files
Directory includes folder selection and attachment bypass when dropping. The path is read from originFileObj.webkitRelativePath; The folder structure is not sent to the server automatically. BeforeUpload returns false: the files remain local.
In folder mode, accept filters .txt to beforeUpload. "Trust accept dialog" sets filter:'native' and disables this filtering in the code. Multiple remains a separate prop: directory does not automatically enable it and does not truncate attachments to a single file.
Select folder and attachments
directory in Upload and Dragger, relative paths, multiple and accept. The folder is selected by the native dialog or transferred to the area; beforeUpload leaves the files locally.
<script lang="ts">
import {
Button, Checkbox, Upload, UploadDragger,
type UploadFile, type UploadProps
} from '@woodger/antd';
let directory = $state(true);
let dragger = $state(true);
let multiple = $state(true);
let disabled = $state(false);
let nativeFilter = $state(false);
let files = $state.raw<UploadFile[]>([]);
let batches = $state<string[]>([]);
let root = $state<HTMLSpanElement>();
let input = $state<HTMLInputElement>();
const props = $derived<UploadProps>({
directory,
multiple,
disabled,
accept: nativeFilter ? { format: '.txt', filter: 'native' } : '.txt',
fileList: files,
beforeUpload: (file, batch) => {
batches.push(batch.map(item => item.webkitRelativePath || item.name).join(', '));
return false;
},
onChange: info => { files = info.fileList; }
});
</script>
<style>
.example {
display: grid;
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={directory}>{("Select entire folder")}</Checkbox>
<Checkbox bind:checked={dragger}>{("Folder via UploadDragger")}</Checkbox>
<Checkbox bind:checked={multiple}>{("Multiple when selecting a folder")}</Checkbox>
<Checkbox bind:checked={nativeFilter}>{("Trust accept dialogue")}</Checkbox>
<Checkbox bind:checked={disabled}>{("Block folder selection")}</Checkbox>
</div>
{#if dragger}
<UploadDragger {...props} bind:nativeElement={root} bind:inputElement={input}>
<p>{("Click or drag a folder with text files")}</p>
</UploadDragger>
{:else}
<Upload {...props} bind:nativeElement={root} bind:inputElement={input}>
<Button {disabled}>{("Select a folder with text files")}</Button>
</Upload>
{/if}
<output aria-label={("Folder file paths")}>
{(files.map(file => file.originFileObj?.webkitRelativePath || file.name).join('; ')
|| ("No folder selected"))}
</output>
<output aria-label={("Batch files folder")}>{(batches.join(' | ')
|| ("No checks"))}</output>
<output aria-label={("Roots of folder selection")}>{(root && input ? "Connected" : "Waiting mount")}</output>
<p>
{("Directory includes folder selection and attachment bypass when dropping. The path is read from originFileObj.webkitRelativePath; The folder structure is not sent to the server automatically. BeforeUpload returns false: the files remain local.")}
</p>
<p>
{("In folder mode, accept filters .txt to beforeUpload. \"Trust accept dialog\" sets filter:'native' and disables this filtering in the code. Multiple remains a separate prop: directory does not automatically enable it and does not truncate attachments to a single file.")}
</p>
</div>
IconRender gets the current file and listType, including the uploading state. An empty snippet does not return the default icon; the number 0 is displayed. The finished image in picture views has priority over the icon.
Initial states are specified for comparison. New files stay local: beforeUpload returns false.
Custom file icons
iconRender as Svelte snippet with file/listType: states, empty result, number 0 and priority of the finished thumbnail in picture views.
<script lang="ts">
import { Button, Checkbox, Upload, type UploadFile, type UploadProps } from '@woodger/antd';
let listType = $state<NonNullable<UploadProps['listType']>>('text');
let mode = $state('custom');
let thumbnail = $state(false);
const thumb = 'data:image/svg+xml,' + encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" rx="8" fill="#52c41a"/></svg>'
);
let files = $state.raw<UploadFile[]>([
{ uid: 'cover', name: 'cover.png', type: 'image/png', status: 'done' },
{ uid: 'error', name: 'error.txt', status: 'error', response: "Local file error" },
{ uid: 'pending', name: 'pending.txt', status: 'uploading', percent: 40 }
]);
const displayed = $derived(files.map(file => file.uid === 'cover'
? { ...file, thumbUrl: thumbnail ? thumb : undefined }
: file));
</script>
<style>
.example {
display: grid;
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
label {
display: grid;
gap: 6px;
}
select {
max-width: 100%;
padding: 4px 8px;
border: 1px solid var(--ant-color-border);
border-radius: 6px;
background: var(--ant-color-bg-container);
color: var(--ant-color-text);
font: inherit;
}
.file-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
border: 1px solid currentColor;
border-radius: 3px;
color: var(--ant-color-success);
font-size: 8px;
font-weight: 700;
line-height: 1;
}
.file-icon.error { color: var(--ant-color-error); }
.file-icon.pending { color: var(--ant-color-primary); }
p { margin: 0; }
</style>
{#snippet fileIcon(file: UploadFile, currentType: NonNullable<UploadProps['listType']>)}
{#if mode === 'zero'}0{:else if mode !== 'empty'}
<span class="file-icon" class:error={file.status === 'error'}
class:pending={file.status === 'uploading'} role="img"
aria-label={("Icon " + String((file.name)) + ": " + String((currentType)) + ": " + String((file.status ?? ("local"))) + "")}>
{(file.name.endsWith('.png') ? 'PNG' : 'TXT')}
</span>
{/if}
{/snippet}
<div class="example">
<div class="controls">
<label>{("List view with its own icons\n ")}<select bind:value={listType}>
<option value="text">text</option><option value="picture">picture</option>
<option
value="picture-card"
>picture-card</option><option
value="picture-circle"
>picture-circle</option>
</select>
</label>
<label>{("Drawing a file icon\n ")}<select bind:value={mode}>
<option
value="custom"
>{("Custom icon")}</option><option
value="default"
>{("Standard")}</option>
<option
value="empty"
>{("Empty snippet")}</option><option
value="zero"
>{("Number 0")}</option>
</select>
</label>
<Checkbox bind:checked={thumbnail}>{("Finished miniature cover.png")}</Checkbox>
</div>
<Upload {listType} fileList={(displayed)} iconRender={mode === 'default'
? undefined
: fileIcon}
beforeUpload={() => false} onChange={info => { files = info.fileList; }}>
<Button>{("Add a file with your icon")}</Button>
</Upload>
<p>
{("IconRender gets the current file and listType, including the uploading state. An empty snippet does not return the default icon; the number 0 is displayed. The finished image in picture views has priority over the icon.")}
</p>
<p>
{("Initial states are specified for comparison. New files stay local: beforeUpload returns false.")}
</p>
</div>
Position 1 from 3
Position 2 from 3
Position 3 from 3
Drag the line or use "Above" and "Below". The order is determined by the application's fileList; a persistent uid preserves the line and its note. OriginNode - snippet of a standard line with Tooltip error.
Actions call callbacks Upload; disabled and the availability of its buttons is determined by the application. Policy.txt is protected via onRemove. Downloading here only shows the name; new files are not sent.
Own line and file order
itemRender gets originNode, file, current list and actions. Sorting by drag and drop or buttons saves notes; viewing, downloading and veto deletion are associated with callbacks Upload.
<script lang="ts">
import { tick, type Snippet } from 'svelte';
import {
Button, Checkbox, Input, Modal, Upload,
type UploadFile, type UploadItemRenderActions
} from '@woodger/antd';
let custom = $state(true);
let origin = $state(true);
let disabled = $state(false);
let preview = $state('');
let downloaded = $state('');
let removed = $state('');
let root = $state<HTMLSpanElement>();
let notes = $state<Record<string, string>>({});
let files = $state.raw<UploadFile[]>([
{ uid: 'alpha', name: 'alpha.txt', status: 'done' },
{ uid: 'beta', name: 'beta.txt', status: 'error', response: "Local error beta.txt" },
{ uid: 'policy', name: 'policy.txt', status: 'done' }
]);
async function move(uid: string, target: number) {
const index = files.findIndex(file => file.uid === uid);
if (disabled || index < 0 || target < 0 || target >= files.length || index === target) {
return;
}
const focused = document.activeElement;
const next = [...files];
const movedFiles = next.splice(index, 1);
next.splice(target, 0, ...movedFiles);
files = next;
await tick();
if (focused instanceof HTMLElement && root?.contains(focused)
&& (document.activeElement === document.body || document.activeElement === focused)) {
const boundaryButton = focused instanceof HTMLButtonElement
&& (target === 0 || target === next.length - 1);
const focusTarget = boundaryButton
? focused.closest<HTMLElement>('.row')
: focused;
focusTarget?.focus({ preventScroll: true });
}
}
</script>
<style>
.example, .row {
display: grid;
gap: 12px;
min-width: 0;
}
.controls, .actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.row {
margin-top: 12px;
padding: 12px;
border: 1px solid var(--ant-color-border-secondary);
border-radius: 8px;
background: var(--ant-color-bg-container);
}
.row[draggable="true"] { cursor: grab; }
.row:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
.row p { overflow-wrap: anywhere; }
.editor {
display: grid;
gap: 6px;
min-width: 0;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
{#snippet row(
originNode: Snippet,
file: UploadFile,
fileList: readonly UploadFile[],
actions: UploadItemRenderActions
)}
{@const firstFile = disabled ? undefined : fileList[0]}
{@const lastFile = disabled ? undefined : fileList.at(-1)}
<section
class="row"
aria-label={("String " + String((file.name)) + "")}
tabindex="-1"
draggable={!disabled}
ondragstart={event => {
event.dataTransfer?.setData('application/x-upload-row', file.uid);
if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move';
}}
ondragover={event => {
if (event.dataTransfer?.types.includes('application/x-upload-row')) event.preventDefault();
}}
ondrop={event => {
const uid = event.dataTransfer?.getData('application/x-upload-row');
if (!uid) {
return;
}
event.preventDefault();
event.stopPropagation();
void move(uid, fileList.findIndex(item => item.uid === file.uid));
}}
>
{#if origin}{@render originNode()}{:else}<p>{file.name} · {(file.status ?? "local")}</p>{/if}
<p>{("Position ")}{(fileList.findIndex(item => item.uid === file.uid) + 1)}{(" from ")}{(fileList.length)}</p>
<label class="editor">{("Note ")}{file.name}
<Input bind:value={notes[file.uid]} {disabled} />
</label>
<div class="actions">
<Button
{disabled}
aria-label={("View " + String((file.name)) + "")}
onclick={actions.preview}
>{("View")}</Button>
<Button {disabled} aria-label={("Download " + String((file.name)) + "")} onclick={actions
.download}>{("Download")}</Button>
<Button {disabled} aria-label={("Delete " + String((file.name)) + "")} onclick={actions
.remove}>{("Delete")}</Button>
<Button disabled={disabled || firstFile?.uid === file.uid}
aria-label={("Above " + String((file.name)) + "")} onclick={() => {
const uid = file.uid;
const index = fileList.findIndex(item => item.uid === uid);
move(uid, index - 1);
}}>{("Above")}</Button>
<Button disabled={disabled || lastFile?.uid === file.uid}
aria-label={("Below " + String((file.name)) + "")} onclick={() => {
const uid = file.uid;
const index = fileList.findIndex(item => item.uid === uid);
move(uid, index + 1);
}}>{("Below")}</Button>
</div>
</section>
{/snippet}
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("Your list lines Upload")}</Checkbox>
<Checkbox bind:checked={origin}>{("Save originNode")}</Checkbox>
<Checkbox bind:checked={disabled}>{("Block your lines")}</Checkbox>
</div>
<Upload {disabled} fileList={(files)} bind:nativeElement={root} itemRender={custom
? row
: undefined}
beforeUpload={() => false} onChange={info => { files = info.fileList; }}
onPreview={file => { preview = file.name; }}
onDownload={file => { downloaded = file.name; }}
onRemove={file => {
const allowed = !disabled && file.uid !== 'policy';
removed = ("" + String((allowed ? ("Deleted") : ("Removal prohibited"))) + ": " + String((file.name)) + "");
return allowed;
}}>
<Button {disabled}>{("Add file to your list")}</Button>
</Upload>
<output aria-label={("Order your list")}>{(files.map(
file => file.name
).join(', ')
|| ("Empty"))}</output>
<output aria-label={("Downloading your string")}>{(downloaded
|| ("No download"))}</output>
<output aria-label={("Deleting your line")}>{(removed
|| ("No deletion"))}</output>
<p>
{("Drag the line or use \"Above\" and \"Below\". The order is determined by the application's fileList; a persistent uid preserves the line and its note. OriginNode - snippet of a standard line with Tooltip error.")}
</p>
<p>
{("Actions call callbacks Upload; disabled and the availability of its buttons is determined by the application. Policy.txt is protected via onRemove. Downloading here only shows the name; new files are not sent.")}
</p>
</div>
<Modal open={Boolean(preview)} title={("Your line information")} footer={null}
onCancel={() => { preview = ''; }}>
<p>{preview}</p>
</Modal>
LinkProps changes the name link attributes. Href is always taken from file.url. Without a url, link attributes are not applied; the thumbnail and the separate preview button also do not receive them.
Onclick is executed before onPreview. PreventDefault cancels preview, return false and stopPropagation do not. JSON passes attributes without onclick function; invalid JSON throws a SyntaxError. To download a local text example, turn off onPreview and leave the return false handler.
File name link attributes
UploadFile.linkProps as object or JSON: class, style, download, available name and onclick. The order is onclick/onPreview, preventDefault, no url and native download of local text.
<script lang="ts">
import type { HTMLAnchorAttributes } from 'svelte/elements';
import { Checkbox, Input, Modal, Upload, type UploadFile } from '@woodger/antd';
let json = $state(false);
let hasUrl = $state(true);
let withPreview = $state(true);
let clickMode = $state('continue');
let draft = $state(("Note next to the link"));
let preview = $state('');
let events = $state<string[]>([]);
const url = '/examples/upload/notes.txt';
const attributes: HTMLAnchorAttributes = {
target: '_self',
rel: 'noopener',
title: "Text example Upload",
download: 'notes.txt',
href: '#link-props-ignored',
class: 'upload-demo-filename',
style: 'font-weight:600',
'aria-label': "Download example notes.txt",
'data-file-link': 'filename'
};
const linkProps = $derived<UploadFile['linkProps']>(json
? JSON.stringify(attributes)
: {
...attributes,
onclick: event => {
events.push('link');
if (clickMode === 'prevent') event.preventDefault();
if (clickMode === 'stop') event.stopPropagation();
return false;
}
});
const file = $derived<UploadFile>({
uid: 'filename',
name: 'notes.txt',
status: 'done',
url: hasUrl ? url : undefined,
linkProps
});
</script>
<style>
.example {
display: grid;
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
label {
display: grid;
gap: 6px;
}
select {
max-width: 100%;
padding: 4px 8px;
border: 1px solid var(--ant-color-border);
border-radius: 6px;
background: var(--ant-color-bg-container);
color: var(--ant-color-text);
font: inherit;
}
.example :global(.upload-demo-filename) {
flex: 1;
min-width: 0;
overflow: hidden;
color: var(--ant-color-primary);
text-overflow: ellipsis;
white-space: nowrap;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={json}>{("LinkProps as JSON")}</Checkbox>
<Checkbox bind:checked={hasUrl}>{("Send file url")}</Checkbox>
<Checkbox bind:checked={withPreview}>{("Link name to onPreview")}</Checkbox>
<label>{("Name reference handler\n ")}<select
bind:value={clickMode}
disabled={json}
>
<option value="continue">return false</option>
<option value="prevent">preventDefault</option>
<option value="stop">stopPropagation</option>
</select>
</label>
</div>
<Input aria-label={("Note next to file link")} bind:value={draft} />
<Upload
fileList={([file])}
showUploadList={({ showRemoveIcon: false })}
onPreview={withPreview ? current => {
events.push('preview');
preview = current.name;
} : undefined}
/>
<output aria-label={("Order of link events")}>{(events.join(' → ')
|| ("No events"))}</output>
<p>
{("LinkProps changes the name link attributes. Href is always taken from file.url. Without a url, link attributes are not applied; the thumbnail and the separate preview button also do not receive them.")}
</p>
<p>
{("Onclick is executed before onPreview. PreventDefault cancels preview, return false and stopPropagation do not. JSON passes attributes without onclick function; invalid JSON throws a SyntaxError. To download a local text example, turn off onPreview and leave the return false handler.")}
</p>
</div>
<Modal open={Boolean(preview)} title={("File link information")} footer={null}
onCancel={() => { preview = ''; }}>
<p>{preview}</p>
</Modal>
Pictures in the list
picture shows a thumbnail next to the file name. The initial data and added images use the same list.
<script lang="ts">
import { onDestroy } from 'svelte';
import { Button, Modal, Upload, type UploadFile } from '@woodger/antd';
const thumbnail = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="160" height="120" viewBox="0 0 160 120"><rect width="160" height="120" fill="#f9f0ff"/><rect x="24" y="24" width="112" height="72" rx="12" fill="#722ed1"/><circle cx="80" cy="60" r="20" fill="#fff"/></svg>'
);
const initial: UploadFile[] = [{
uid: 'picture',
name: 'interface.svg',
status: 'done',
thumbUrl: thumbnail
}];
let preview = $state('');
let ownedPreview: string | undefined;
function closePreview() {
if (ownedPreview) URL.revokeObjectURL(ownedPreview);
ownedPreview = undefined;
preview = '';
}
function showPreview(file: UploadFile) {
closePreview();
preview = file.url ?? file.thumbUrl ?? '';
if (!preview && file.originFileObj) {
ownedPreview = URL.createObjectURL(file.originFileObj);
preview = ownedPreview;
}
}
onDestroy(closePreview);
</script>
<style>
.preview {
display: block;
max-width: 100%;
max-height: 60vh;
margin: auto;
}
</style>
<Upload
onPreview={showPreview}
defaultFileList={(initial)}
listType="picture"
accept="image/*"
beforeUpload={() => false}
>
<Button>{("Add image to list")}</Button>
</Upload>
<Modal
open={Boolean(preview)}
title={("File preview")}
footer={null}
onCancel={closePreview}
>
{#if preview}<img
class="preview"
src={preview}
alt={("Image preview")}
/>{/if}
</Modal>
Your own file thumbnail
previewFile returns a Promise with the source of the thumbnail. In the example, the text files receive a generic SVG thumbnail; the file is not transferred to the server.
<script lang="ts">
import { Button, Modal, Upload } from '@woodger/antd';
const thumbnail = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="160" height="120" viewBox="0 0 160 120"><rect width="160" height="120" fill="#f9f0ff"/><rect x="24" y="24" width="112" height="72" rx="12" fill="#722ed1"/><circle cx="80" cy="60" r="20" fill="#fff"/></svg>'
);
let preview = $state(false);
</script>
<Upload
onPreview={() => { preview = true; }}
listType="picture"
accept=".txt,text/plain"
beforeUpload={() => false}
previewFile={async () => thumbnail}
isImageUrl={() => true}
>
<Button>{("Add text with thumbnail")}</Button>
</Upload>
<Modal open={preview} title={("Sketch file")} footer={null} onCancel={() => {
preview = false;
}}>
<img
src={thumbnail}
alt={("General sketch of the text file")}
style="
display: block;
max-width: 100%;
margin: auto;
"
/>
</Modal>
One file
Up to three files
Quantity limit
maxCount=1 replaces the previous file. In multiple, the list is limited to three files.
<script lang="ts">
import { Button, Upload } from '@woodger/antd';
</script>
<style>
.examples {
display: grid;
gap: 24px;
}
p {
margin: 0 0 12px;
}
</style>
<div class="examples">
<div><p>{("One file")}</p><Upload
maxCount={1}
beforeUpload={() => false}
><Button>{("Select one file")}</Button></Upload></div>
<div><p>{("Up to three files")}</p><Upload
maxCount={3}
multiple
beforeUpload={() => false}
><Button>{("Select up to three files")}</Button></Upload></div>
</div>
Pre-query conversion
beforeUpload returns a Blob with the title before the source text. customRequest reads the converted bytes and validates the local result.
<script lang="ts">
import { Button, Upload, type UploadRcFile, type UploadRequestOptions } from '@woodger/antd';
let body = $state('');
async function transform(file: UploadRcFile) {
return new Blob(['# Demo\n', await file.text()], { type: 'text/plain' });
}
function request(options: UploadRequestOptions) {
let active = true;
void options.file.text().then(text => {
if (!active) {
return;
}
body = text;
options.onSuccess?.({ demo: true });
}).catch(error => {
if (active) {
options.onError?.(
error instanceof Error
? error
: new Error((String(error)))
);
}
});
return { abort: () => { active = false; } };
}
</script>
<style>
pre {
max-width: 100%;
max-height: 180px;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
<Upload accept=".txt,text/plain" beforeUpload={transform} customRequest={request}>
<Button>{("Convert text")}</Button>
</Upload>
<pre><output aria-label={("Prepared request body")}>{(body
|| ("No text selected yet"))}</output></pre>
List actions and additional information
showUploadList controls the visibility of actions for each file, extra adds information. The action icons are shown separately in the following example.
<script lang="ts">
import { Button, Upload, type UploadFile } from '@woodger/antd';
const initial: UploadFile[] = [
{ uid: 'locked', name: 'readme.txt', size: 128, status: 'done' },
{ uid: 'editable', name: 'draft.txt', size: 64, status: 'done' }
];
let downloaded = $state('');
</script>
{#snippet extra(file: UploadFile)}
<small> · {(file.size ?? 0)}{(" bytes")}</small>
{/snippet}
<Upload defaultFileList={(initial)} beforeUpload={() => false}
showUploadList={({
extra,
showRemoveIcon: file => file.uid !== 'locked',
showDownloadIcon: true
})}
onDownload={file => { downloaded = file.name; }}>
<Button>{("Add information file")}</Button>
</Upload>
<p><output aria-label={("Requested file upload")}>{(downloaded
|| ("Loading not requested"))}</output></p>
Snippets receive the current file and change the contents of standard actions. An empty snippet leaves the control with an accessible name; to hide use show*Icon. Preview is shown in card/circle, download - only for done. Disabled blocks deletion, viewing and downloading remain available.
Callbacks here show the file name; draft.svg is protected via onRemove. Undefined returns the default icon, the number 0 is displayed. New files remain locally without being sent.
Action icons and information
Snippets previewIcon/downloadIcon/removeIcon get the file. Visibility, available names and callbacks remain standard; own, empty and standard icons are compared.
<script lang="ts">
import {
Button, Checkbox, Input, Modal, Upload,
type UploadFile, type UploadListOptions, type UploadProps
} from '@woodger/antd';
let mode = $state('custom');
let listType = $state<NonNullable<UploadProps['listType']>>('picture-card');
let disabled = $state(false);
let onlyMap = $state(true);
let preview = $state('');
let downloaded = $state('');
let removed = $state('');
let draft = $state(("Note next to the icons"));
let files = $state.raw<UploadFile[]>([
{
uid: 'map',
name: 'map.svg',
status: 'done',
size: 128,
url: '/examples/image/geometry.svg',
thumbUrl: '/examples/image/geometry.svg'
},
{
uid: 'draft',
name: 'draft.svg',
status: 'done',
size: 64,
url: '/examples/image/coast.svg',
thumbUrl: '/examples/image/coast.svg'
}
]);
const options = $derived<UploadListOptions>({
extra,
showPreviewIcon: true,
showDownloadIcon: file => !onlyMap || file.uid === 'map',
showRemoveIcon: true,
previewIcon: mode === 'default' ? undefined : previewIcon,
downloadIcon: mode === 'default' ? undefined : downloadIcon,
removeIcon: mode === 'default' ? undefined : removeIcon
});
</script>
<style>
.example {
display: grid;
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
label {
display: grid;
gap: 6px;
min-width: 0;
}
select {
max-width: 100%;
padding: 4px 8px;
border: 1px solid var(--ant-color-border);
border-radius: 6px;
background: var(--ant-color-bg-container);
color: var(--ant-color-text);
font: inherit;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
{#snippet glyph(action: string, file: UploadFile)}
{#if mode === 'zero'}{(0)}{:else if mode !== 'empty'}
<svg data-upload-action={action} data-file={file.name} aria-hidden="true" focusable="false"
viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor"
stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
{#if action === 'preview'}
<circle cx="10" cy="10" r="6" /><path d="m15 15 5 5" />
{:else if action === 'download'}
<path d="M12 3v12m-4-4 4 4 4-4M4 17v4h16v-4" />
{:else}
<path d="m6 6 12 12M18 6 6 18" />
{/if}
</svg>
{/if}
{/snippet}
{#snippet previewIcon(file: UploadFile)}{@render glyph('preview', file)}{/snippet}
{#snippet downloadIcon(file: UploadFile)}{@render glyph('download', file)}{/snippet}
{#snippet removeIcon(file: UploadFile)}{@render glyph('remove', file)}{/snippet}
{#snippet extra(file: UploadFile)}
<small> · {(file.size ?? 0)}{(" bytes")}</small>
{/snippet}
<div class="example">
<div class="controls">
<label>{("Upload action icons\n ")}<select bind:value={mode}>
<option value="custom">
{("Own")}
</option>
<option value="default">
{("Standard")}
</option>
<option
value="empty"
>{("Empty snippets")}</option>
<option
value="zero"
>{("Number 0")}</option>
</select>
</label>
<label>{("List view with actions\n ")}<select bind:value={listType}>
<option value="text">text</option><option value="picture">picture</option>
<option
value="picture-card"
>picture-card</option><option
value="picture-circle"
>picture-circle</option>
</select>
</label>
<Checkbox bind:checked={disabled}>{("Disable download and delete")}</Checkbox>
<Checkbox bind:checked={onlyMap}>{("Download only map.svg")}</Checkbox>
</div>
<Input aria-label={("Note next to action icons")} bind:value={draft} />
<Upload {listType} {disabled} fileList={(files)} showUploadList={(options)}
beforeUpload={() => false} onChange={info => { files = info.fileList; }}
onPreview={file => { preview = file.name; }}
onDownload={file => { downloaded = file.name; }}
onRemove={file => {
const allowed = file.uid !== 'draft';
removed = ("" + String((allowed ? ("Deleted") : ("Removal prohibited"))) + ": " + String((file.name)) + "");
return allowed;
}}>
<Button {disabled}>{("Add")}</Button>
</Upload>
<output aria-label={("Download via your icon")}>{(downloaded
|| ("No download"))}</output>
<output aria-label={("Delete via your icon")}>{(removed
|| ("No deletion"))}</output>
<output aria-label={("Files with action icons")}>{(files.map(file => file.name)
.join(', ')
|| ("Empty"))}</output>
<p>
{("Snippets receive the current file and change the contents of standard actions. An empty snippet leaves the control with an accessible name; to hide use show*Icon. Preview is shown in card/circle, download - only for done. Disabled blocks deletion, viewing and downloading remain available.")}
</p>
<p>
{("Callbacks here show the file name; draft.svg is protected via onRemove. Undefined returns the default icon, the number 0 is displayed. New files remain locally without being sent.")}
</p>
</div>
<Modal open={Boolean(preview)} title={("Upload action details")} footer={null}
onCancel={() => { preview = ''; }}>
<p>{preview}</p>
</Modal>
General and local settings
Inherited Dragger
Empty nested record
Sample.txt - sample band with 42%. New files are processed locally: Click End Requests. In the reset scope, beforeUpload returns false to avoid running the standard XHR.
An empty upload inherits the entire record; an empty nested record replaces it. The classes are accumulated, local CSS lines are applied after the general ones. Progress is merged across fields: an empty local object stores the overall progress. Changing customRequest affects the following files, current requests continue; hiding Upload cancels incomplete ones.
General settings Upload
ConfigProvider.upload: inheritance, record reset, local styles/accept, progress merge and transport selection. Unfinished requests are saved when changing settings and are canceled when unmounted.
ProviderUpload.svelte<script lang="ts"> import { Button, Checkbox, ConfigProvider, Input, type UploadConfig, type UploadProps, type UploadRequestOptions } from '@woodger/antd'; import ProviderUploadScope from './ProviderUploadScope.svelte'; let localRequest = $state(false); let localStyles = $state(true); let clearAccept = $state(false); let wide = $state(false); let mounted = $state(true); let progressMode = $state('inherit'); let draft = $state(("Note next to provider")); let requests = $state<string[]>([]); let aborted = $state<string[]>([]); let pending = $state.raw<{ source: string; options: UploadRequestOptions; active: boolean; }[]>([]); function transport(source: string): NonNullable<UploadProps['customRequest']> { return options => { const job = { source, options, active: true }; pending = [...pending, job]; requests.push(`${source}: ${options.file.name}`); options.onProgress?.({ percent: 30 }); return { abort: () => { job.active = false; pending = pending.filter(entry => entry !== job); aborted.push(`${source}: ${options.file.name}`); } }; }; } const providerRequest = transport('provider'); const ownRequest = transport('local'); const shared = $derived<UploadConfig>({ accept: '.txt', class: 'provider-upload-record', classNames: { root: 'provider-upload-root', item: 'provider-upload-item' }, styles: { root: ` display: block; min-width: 0; padding: 12px; border: 1px solid var(--ant-color-primary); border-radius: 8px; `, item: 'min-height:36px', trigger: 'padding-top:6px' }, style: 'padding-top:10px', progress: { size: [-1, wide ? 7 : 5], showInfo: true, strokeColor: '#d46b08' }, customRequest: providerRequest }); const localProgress = $derived.by<UploadProps['progress']>(() => { if (progressMode === 'empty') { return {}; } if (progressMode === 'hide') { return { showInfo: false }; } if (progressMode === 'thick') { return { size: [-1, 9] }; } return undefined; }); const local = $derived<UploadConfig>({ accept: clearAccept ? '' : undefined, customRequest: localRequest ? ownRequest : undefined, classNames: localStyles ? { root: 'local-upload-root', item: 'local-upload-item' } : {}, styles: localStyles ? { root: 'padding-top:8px', trigger: 'padding-top:14px' } : {}, progress: localProgress }); function complete() { const jobs = pending; pending = []; for (const job of jobs) { if (!job.active) { continue; } job.active = false; job.options.onSuccess?.({ source: job.source }); } } </script> <style> .example, .scopes { display: grid; gap: 20px; min-width: 0; } .controls { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; } label { display: grid; gap: 6px; min-width: 0; } select { max-width: 100%; padding: 4px 8px; border: 1px solid var(--ant-color-border); border-radius: 6px; background: var(--ant-color-bg-container); color: var(--ant-color-text); font: inherit; } p { margin: 0; } output { overflow-wrap: anywhere; } </style> <div class="example"> <div class="controls"> <Checkbox bind:checked={localRequest} >{("Local customRequest first Upload")}</Checkbox> <Checkbox bind:checked={localStyles} >{("Local styles of the first Upload")}</Checkbox> <Checkbox bind:checked={clearAccept}>{("Empty local accept")}</Checkbox> <Checkbox bind:checked={wide}>{("Increase overall progress")}</Checkbox> <Checkbox bind:checked={mounted}>{("Show Upload with settings")}</Checkbox> <label>{("Local progress of the first Upload\n ")}<select bind:value={progressMode} > <option value="inherit" >{("Inherit")}</option> <option value="empty" >{("Empty object")}</option> <option value="hide"> {("Without label")} </option> <option value="thick"> {("Thickness 9px")} </option> </select> </label> </div> <Input aria-label={("Note next to ConfigProvider.upload")} bind:value={draft} /> <ConfigProvider upload={shared}> {#if mounted} <div class="scopes"> <ProviderUploadScope id="local" title={("General and local settings")} overrides={local} /> <ConfigProvider> <ProviderUploadScope id="inherited" title={("Inherited Dragger")} dragger /> </ConfigProvider> <ConfigProvider upload={{}}> <ProviderUploadScope id="reset" title={("Empty nested record")} manual /> </ConfigProvider> </div> {/if} </ConfigProvider> <Button disabled={pending.length === 0} onclick={complete} >{("End requests")}</Button> <output aria-label={("Requests ConfigProvider.upload")}>{(requests.join('; ') || ("No requests"))}</output> <output aria-label={("Pending Upload requests")} >{("Expect: ")}{(pending.length)}</output> <output aria-label={("Canceled Upload requests")}>{(aborted.join('; ') || ("No cancellations"))}</output> <p> {("Sample.txt - sample band with 42%. New files are processed locally: Click End Requests. In the reset scope, beforeUpload returns false to avoid running the standard XHR.")} </p> <p> {("An empty upload inherits the entire record; an empty nested record replaces it. The classes are accumulated, local CSS lines are applied after the general ones. Progress is merged across fields: an empty local object stores the overall progress. Changing customRequest affects the following files, current requests continue; hiding Upload cancels incomplete ones.")} </p> </div>ProviderUploadScope.svelte<script lang="ts"> import { untrack } from 'svelte'; import { Button, Upload, UploadDragger, type UploadConfig, type UploadFile } from '@woodger/antd'; let { id, title, overrides = {}, manual = false, dragger = false }: { id: string; title: string; overrides?: UploadConfig; manual?: boolean; dragger?: boolean; } = $props(); let files = $state.raw<UploadFile[]>(untrack(() => [ { uid: `${id}-sample`, name: 'sample.txt', status: 'uploading', percent: 42, 'aria-label': `Progress sample: ${title}` } ])); let root = $state<HTMLSpanElement>(); let input = $state<HTMLInputElement>(); </script> <style> section { display: grid; gap: 12px; min-width: 0; padding: 12px; border: 1px solid var(--ant-color-border-secondary); border-radius: 8px; } h4, p { margin: 0; } .widget { min-width: 0; padding-bottom: 24px; } output { overflow-wrap: anywhere; } </style> <section aria-label={(title)}> <h4>{(title)}</h4> <div class="widget"> {#if dragger} <UploadDragger {...overrides} fileList={(files)} bind:nativeElement={root} bind:inputElement={input} beforeUpload={() => manual ? false : undefined} onChange={info => { files = info.fileList; }}> <p>{("Click or drag the file")}</p> </UploadDragger> {:else} <Upload {...overrides} fileList={(files)} bind:nativeElement={root} bind:inputElement={input} beforeUpload={() => manual ? false : undefined} onChange={info => { files = info.fileList; }}> <Button>{("Select file")}</Button> </Upload> {/if} </div> <output aria-label={("Files: " + String((title)) + "")}> {files.map(file => `${file.name}: ${file.status ?? "without sending"}`).join('; ')} </output> <output aria-label={("DOM: " + String((title)) + "")}>{(root && input ? "Connected" : "Waiting mount")}</output> </section>
Locked selection
disabled is passed to Upload and the nested Button so that their accessibility and appearance match.
<script lang="ts">
import { Button, Upload } from '@woodger/antd';
let disabled = $state(true);
</script>
<p><label><input
type="checkbox"
bind:checked={disabled}
/>{(" Block Upload")}</label></p>
<Upload {disabled} beforeUpload={() => false}>
<Button {disabled}>{("Select available file")}</Button>
</Upload>
The percentage and status here are set manually, without a request. In the application, percent is updated from onProgress. The bar appears after the mount line with a delay of 300 ms only when status='uploading' and percent is specified.
Without local and general progress Upload sets size=[-1,2] and showInfo=false. General and local parameters are combined by fields. If there is no common progress, any object replaces defaults Upload; missing fields receive defaults Progress. To change the thickness use size. The name can be set to UploadFile, and progress has priority.
File progress design
Progress as a line settings object: size, color, gradient, steps, format and available name. Percent is stored in UploadFile; the absence of a prop and an empty object give different defaults.
<script lang="ts">
import {
Checkbox, Input, Slider, Upload,
type UploadFile, type UploadListProgressProps, type UploadProps
} from '@woodger/antd';
let mode = $state('color');
let listType = $state<NonNullable<UploadProps['listType']>>('text');
let percent = $state(42);
let uploading = $state(true);
let hasPercent = $state(true);
let commonLabel = $state(false);
let draft = $state(("Note next to progress"));
const progress = $derived.by<UploadListProgressProps | undefined>(() => {
const presets: Record<string, UploadListProgressProps | undefined> = {
default: undefined,
empty: {},
color: { size: [-1, 6], showInfo: true, strokeColor: '#d46b08' },
gradient: {
size: [-1, 8],
showInfo: false,
strokeColor: { from: '#d46b08', to: '#389e0d', direction: 'to right' }
},
steps: { steps: 5, showInfo: false, strokeColor: '#722ed1' },
format: {
size: [-1, 6],
showInfo: true,
format: value => `${value}% transferred`
}
};
const selected = presets[mode];
return commonLabel
? { ...selected, 'aria-label': "General progress Upload" }
: selected;
});
const file = $derived<UploadFile>({
uid: 'transfer',
name: 'archive.zip',
status: uploading ? 'uploading' : 'done',
percent: hasPercent ? percent : undefined,
'aria-label': "Transfer archive.zip"
});
</script>
<style>
.example {
display: grid;
gap: 20px;
min-width: 0;
}
.controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
label {
display: grid;
gap: 6px;
min-width: 0;
}
select {
max-width: 100%;
padding: 4px 8px;
border: 1px solid var(--ant-color-border);
border-radius: 6px;
background: var(--ant-color-bg-container);
color: var(--ant-color-text);
font: inherit;
}
.transfer { padding-bottom: 24px; }
p { margin: 0; }
</style>
<div class="example">
<div class="controls">
<label>{("Upload progress design\n ")}<select bind:value={mode}>
<option
value="default"
>{("Without progress")}</option>
<option
value="empty"
>{("Empty object")}</option>
<option
value="color"
>{("Color and thickness")}</option>
<option
value="gradient"
>{("Gradient")}</option>
<option value="steps">
{("Steps")}
</option>
<option value="format">
{("Own format")}
</option>
</select>
</label>
<label>{("List view with progress\n ")}<select bind:value={listType}>
<option value="text">text</option><option value="picture">picture</option>
<option
value="picture-card"
>picture-card</option><option
value="picture-circle"
>picture-circle</option>
</select>
</label>
<Checkbox bind:checked={uploading}>{("File loading")}</Checkbox>
<Checkbox bind:checked={hasPercent}>{("Transfer percent of the file")}</Checkbox>
<Checkbox
bind:checked={commonLabel}
>{("The name from progress overlaps the file name")}</Checkbox>
</div>
<Slider
aria-label={("Percentage of file Upload")}
bind:value={percent}
min={0}
max={100}
/>
<Input aria-label={("Note next to Upload progress")} bind:value={draft} />
<div class="transfer">
<Upload {listType} {progress} fileList={([file])} showUploadList={({
showRemoveIcon: false
})} />
</div>
<output
aria-label={("Upload progress status")}
>{(file.status)}: {(file.percent ?? "without percent")}</output>
<p>
{("The percentage and status here are set manually, without a request. In the application, percent is updated from onProgress. The bar appears after the mount line with a delay of 300 ms only when status='uploading' and percent is specified.")}
</p>
<p>
{("Without local and general progress Upload sets size=[-1,2] and showInfo=false. General and local parameters are combined by fields. If there is no common progress, any object replaces defaults Upload; missing fields receive defaults Progress. To change the thickness use size. The name can be set to UploadFile, and progress has priority.")}
</p>
</div>
Root designs a wrapper, list - a list, item - a regular line, trigger - a selection area or Dragger. Class and rootClassName complement classNames.root. CSS styles are applied to the relevant parts; regular style overrides styles.trigger.
Callback receives props with defaults and disabled enabled from the current context. Here it changes the line height when disabled. When completely replacing the originNode via itemRender, the item slot is not displayed. New files are saved locally, without being sent.
Semantic DOM list and selection area
Root/list/item/trigger via classNames and CSS lines styles: object, callback, Dragger and priority of normal style. Files and external editor are saved when changing the design.
<script lang="ts">
import {
Button, Checkbox, Input, Upload, UploadDragger,
type UploadFile, type UploadProps, type UploadSemanticInfo, type UploadSemanticSlots
} from '@woodger/antd';
let mode = $state('object');
let listType = $state<NonNullable<UploadProps['listType']>>('text');
let dragger = $state(false);
let disabled = $state(false);
let priority = $state(false);
let draft = $state(("Note next to the design"));
let files = $state.raw<UploadFile[]>([
{ uid: 'report', name: 'report.txt', status: 'done' },
{ uid: 'draft', name: 'draft.txt', status: 'error', response: "Formatted string error" }
]);
let root = $state<HTMLSpanElement>();
let input = $state<HTMLInputElement>();
const names: UploadSemanticSlots = {
root: 'semantic-upload-root',
list: 'semantic-upload-list',
item: 'semantic-upload-item',
trigger: 'semantic-upload-trigger'
};
const slots: UploadSemanticSlots = {
root: `
--upload-example-accent: var(--ant-color-primary);
display: block;
min-width: 0;
padding: 12px;
border: 1px solid var(--upload-example-accent);
border-radius: 8px;
`,
list: 'margin-top:16px',
item: `
min-height: 36px;
padding-inline: 8px;
background: var(--ant-color-fill-tertiary);
border-radius: 4px;
`,
trigger: `
padding: 8px;
color: var(--upload-example-accent);
border: 1px dashed var(--upload-example-accent);
border-radius: 6px;
`
};
const classNames = $derived.by<UploadProps['classNames']>(() => {
if (mode === 'empty') {
return {};
}
if (mode === 'callback') {
return ({ props }: UploadSemanticInfo) => ({
...names,
root: `${names.root} semantic-${props.type}-${props.listType}`
});
}
return names;
});
const styles = $derived.by<UploadProps['styles']>(() => {
if (mode === 'empty') {
return {};
}
if (mode === 'callback') {
return ({ props }: UploadSemanticInfo) => ({
...slots,
item: `
${slots.item}
min-height: ${props.disabled ? 48 : 40}px;
`
});
}
return slots;
});
const props = $derived<UploadProps>({
listType,
disabled,
fileList: files,
class: 'semantic-upload-local',
rootClassName: 'semantic-upload-extra',
classNames,
styles,
style: priority ? 'padding-top:16px' : undefined,
beforeUpload: () => false,
onChange: info => { files = info.fileList; }
});
</script>
<style>
.example {
display: grid;
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
}
label {
display: grid;
gap: 6px;
min-width: 0;
}
select {
max-width: 100%;
padding: 4px 8px;
border: 1px solid var(--ant-color-border);
border-radius: 6px;
background: var(--ant-color-bg-container);
color: var(--ant-color-text);
font: inherit;
}
p { margin: 0; }
</style>
<div class="example">
<div class="controls">
<label>{("Semantic settings Upload\n ")}<select bind:value={mode}>
<option
value="object"
>{("Object")}</option><option
value="callback"
>Callback</option>
<option value="empty">{("Empty settings")}</option>
</select>
</label>
<label>{("View of the designed list\n ")}<select bind:value={listType}>
<option value="text">text</option><option value="picture">picture</option>
<option
value="picture-card"
>picture-card</option><option
value="picture-circle"
>picture-circle</option>
</select>
</label>
<Checkbox bind:checked={dragger}>{("Semantic design Dragger")}</Checkbox>
<Checkbox bind:checked={disabled}>{("Disable registered Upload")}</Checkbox>
<Checkbox
bind:checked={priority}
>{("Normal style above styles.trigger")}</Checkbox>
</div>
<Input aria-label={("Note next to Upload design")} bind:value={draft} />
{#if dragger}
<UploadDragger {...props} bind:nativeElement={root} bind:inputElement={input}>
<p>{("Click or drag the file into the designed area")}</p>
</UploadDragger>
{:else}
<Upload {...props} bind:nativeElement={root} bind:inputElement={input}>
<Button {disabled}>{("Add file")}</Button>
</Upload>
{/if}
<output aria-label={("Upload files")}>{(files.map(file => file.name)
.join(', ')
|| ("Empty"))}</output>
<output aria-label={("Roots of the designed Upload")}>{(root && input ? "Connected" : "Waiting mount")}</output>
<p>
{("Root designs a wrapper, list - a list, item - a regular line, trigger - a selection area or Dragger. Class and rootClassName complement classNames.root. CSS styles are applied to the relevant parts; regular style overrides styles.trigger.")}
</p>
<p>
{("Callback receives props with defaults and disabled enabled from the current context. Here it changes the line height when disabled. When completely replacing the originNode via itemRender, the item slot is not displayed. New files are saved locally, without being sent.")}
</p>
</div>
Component theme Upload
Normal list action color and card size, UploadDragger and theme change during local upload. Requests to the server are not fulfilled.
Theme.svelte<script lang="ts"> import { Button, Checkbox, ConfigProvider, Upload, UploadDragger } from '@woodger/antd'; import type { UploadFile } from '@woodger/antd'; import BasicUpload from './BasicUpload.svelte'; let enabled = $state(true); const tokens = { actionsColor: '#874d00', pictureCardSize: 120 }; const pictures: UploadFile[] = [ { uid: 'cover', name: 'logo.webp', status: 'done', url: '/logo.webp', thumbUrl: '/logo.webp' }, { uid: 'error', name: 'draft.png', status: 'error', error: new Error( ("Demo error") ) } ]; const documents: UploadFile[] = [{ uid: 'guide', name: 'logo.webp', status: 'done', url: '/logo.webp' }]; </script> <style> .settings { margin-bottom: 24px; } .examples { display: grid; gap: 24px; } .add { display: grid; place-content: center; gap: 4px; width: 100%; height: 100%; border: 0; background: transparent; color: inherit; font: inherit; cursor: pointer; } </style> <div class="settings"> <Checkbox bind:checked={enabled}>{("Apply Upload tokens")}</Checkbox> </div> <ConfigProvider theme={{ components: { Upload: enabled ? tokens : {} } }}> <div class="examples"> <div class="theme-progress"><BasicUpload /></div> <Upload class="theme-pictures" listType="picture-card" defaultFileList={(pictures)} beforeUpload={() => false} maxCount={3} showUploadList={({ showPreviewIcon: false })} > <button class="add" type="button" aria-label={("Add file to thematic cards")}> <span aria-hidden="true">+</span>{("Add\n ")}</button> </Upload> <UploadDragger class="theme-dragger" defaultFileList={(documents)} beforeUpload={() => false} > <p class="ant-upload-text">{("Click or drag the file")}</p> <p class="ant-upload-hint">{("The file will remain in the local list.")}</p> </UploadDragger> </div> </ConfigProvider>BasicUpload.svelte<script lang="ts"> import { Button, Upload, type UploadFile, type UploadRequestOptions } from '@woodger/antd'; let control = $state<InstanceType<typeof Upload>>(); let files = $state.raw<UploadFile[]>([]); function request(options: UploadRequestOptions) { const progress = setTimeout(() => { options.onProgress?.({ percent: 50 }); }, 350); const completion = setTimeout(() => { if (options.file.name.endsWith('.fail')) { options.onError?.(new Error(("Demo boot error"))); } else { options.onSuccess?.({ demo: true }); } }, 800); return { abort() { clearTimeout(progress); clearTimeout(completion); } }; } function handleAbort() { control?.abort(); files = files.map(file => file.status === 'uploading' ? { ...file, status: 'error', error: new Error(("Loading cancelled.")) } : file); } </script> <style> output { overflow-wrap: anywhere; } </style> <Upload bind:this={control} fileList={(files)} multiple customRequest={request} onChange={info => { files = info.fileList; }} > <Button>{("Select files")}</Button> </Upload> <p><Button disabled={!files.some(file => file.status === 'uploading')} onclick={handleAbort} >{("Cancel requests")}</Button></p> <p><output aria-label={("Download status")}>{(files.map( file => `${file.name}: ${file.status ?? 'pending'} (${file.percent ?? 0}%)` ).join('; ') || ("No files selected"))}</output></p>
Click or drag files
Select multiple files and start downloading manually.
The demonstration is performed locally without sending files to the server.
Manual boot start
Original UploadDragger from the review: list, separate launch of local demo download and reset. Files are not sent to the server.
<script lang="ts">
import { UploadDragger, Button, type UploadFile } from '@woodger/antd';
let files = $state.raw<UploadFile[]>([]);
let result = $state('');
let sending = $state(false);
let generation = 0;
async function send() {
const version = ++generation;
sending = true;
files = files.map(file => ({ ...file, status: 'uploading', percent: 0 }));
await Promise.resolve();
if (version !== generation) {
return;
}
result = files.map(file => file.name).join(', ');
files = files.map(
file => ({ ...file, status: 'done', percent: 100, response: { demo: true } })
);
sending = false;
}
</script>
<style>
output {
display: block;
margin-top: 16px;
}
</style>
<div style="max-width:640px">
<UploadDragger
fileList={(files)}
multiple
beforeUpload={() => false}
disabled={sending}
onChange={info => { files = info.fileList; }}
>
<p class="ant-upload-text">{("Click or drag files")}</p>
<p class="ant-upload-hint">
{("Select multiple files and start downloading manually.")}
</p>
</UploadDragger>
<p>{("The demonstration is performed locally without sending files to the server.")}</p>
<div style="
display: flex;
gap: 8px;
flex-wrap: wrap;
">
<Button type="primary" disabled={!files.length} loading={sending} onclick={send}>
{("Start demo download")}
</Button>
<Button
onclick={() => {
generation++;
files = [];
result = '';
sending = false;
}}
>{("Reset files")}</Button>
</div>
<output aria-label={("Uploaded files")}>{result}</output>
</div>
Trigger, list and Upload/Dragger states follow prefixCls. Button, Progress and Tooltip separately inherit the common prefix. Here is manual mode: file selection does not send a network request.
CSS prefixes Upload
Common namespace ConfigProvider and local prefixCls; the state of the component is preserved when the name is changed.
<script lang="ts">
import {
Checkbox,
ConfigProvider,
Upload,
UploadDragger,
Button,
type UploadFile
} from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-upload' : '');
let fileList = $state<UploadFile[]>([]);
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("General prefix Upload suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Local prefix Upload")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'upload-theme' } }}>
<div class="prefix-stage">
<Upload prefixCls={localPrefix} fileList={(fileList)} beforeUpload={() => false}
onChange={info => fileList = info.fileList}>
<Button>{("Select file with prefix")}</Button>
</Upload>
<UploadDragger prefixCls={localPrefix} beforeUpload={() => false}>
{("\n Drag and drop file with prefix\n ")}
</UploadDragger>
<output
aria-label={("Upload files with prefix")}
>{("Files: ")}{(fileList.length)}</output>
</div>
</ConfigProvider>
<output
aria-label={("CSS prefix Upload")}
>{("General: ")}{prefix}{("; local: ")}{(localPrefix
|| ("from the provider"))}</output>
<p>
{("Trigger, list and Upload/Dragger states follow prefixCls. Button, Progress and Tooltip separately inherit the common prefix. Here is manual mode: file selection does not send a network request.")}
</p>
</div>
The methods update the local list without a transport. onSuccess parses JSON; callbacks for a removed uid are ignored. Abort cancels a request without removing the file.
Upload lifecycle methods
UploadRef for Upload and UploadDragger: batch, progress, a JSON response and an error without network requests.
<script lang="ts">
import {
Button,
Upload,
UploadDragger,
type UploadFile,
type UploadRcFile,
type UploadRef
} from '@woodger/antd';
let drag = $state(false);
let control = $state<UploadRef<{ ok: boolean }>>();
let files = $state.raw<UploadFile<{ ok: boolean }>[]>([]);
let file = $state<UploadRcFile>();
let nextId = 0;
function start() {
file = Object.assign(new File(['Local example'], 'report.txt', { type: 'text/plain' }), {
uid: `ref-${++nextId}`
});
control?.onBatchStart([{ file, parsedFile: file }]);
}
</script>
<label><input type="checkbox" checked={drag} onchange={event => {
drag = event.currentTarget.checked;
files = [];
file = undefined;
}} /> UploadDragger</label>
{#if drag}
<UploadDragger bind:this={control} fileList={files} beforeUpload={() => false} onChange={info => {
files = info.fileList;
}}>
<p>{("Choose a local file")}</p>
</UploadDragger>
{:else}
<Upload bind:this={control} fileList={files} beforeUpload={() => false} onChange={info => {
files = info.fileList;
}} hasControlInside>
<Button>{("Choose a local file")}</Button>
</Upload>
{/if}
<div class="actions">
<Button onclick={start}>onBatchStart</Button>
<Button
disabled={!file}
onclick={() => { if (file) control?.onProgress({ percent: 50 }, file); }}
>onProgress</Button>
<Button
disabled={!file}
onclick={() => { if (file) control?.onSuccess('{"ok":true}', file); }}
>onSuccess</Button>
<Button disabled={!file} onclick={() => {
if (file) {
control?.onError(
new Error(("Local demo error")),
undefined,
file
);
}
}}>onError</Button>
<Button disabled={!file} onclick={() => control?.upload?.abort(file)}>upload.abort</Button>
</div>
<output aria-label="UploadRef">{JSON.stringify(files.map(item => ({
uid: item.uid,
status: item.status,
percent: item.percent,
response: item.response
})))}</output>
<output aria-label="Upload DOM refs">native={Boolean(control?.nativeElement)}; input={Boolean(
control?.inputElement
)}; files={control?.fileList.length ?? 0}</output>
<p>
{("The methods update the local list without a transport. onSuccess parses JSON; callbacks for a removed uid are ignored. Abort cancels a request without removing the file.")}
</p>
<style>
label {
display: block;
margin-block-end: 12px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-block: 12px;
}
output + output { margin-block-start: 8px; }
output {
display: block;
overflow-wrap: anywhere;
}
</style>
API
Mapping to 21 Upload live page themes on ant.design. Here are 26 cards with working Svelte examples; missing parameters and individual application integrations are listed explicitly.
| Theme | Example or limitation |
|---|---|
| Upload by clicking | Local transport with progress, error and cancellation. |
| Avatar | PNG/JPEG check and local image. |
| Default Files | Initial done/uploading/error. |
| Pictures Wall | Controllable Wall, Miniatures and Modal. |
| Pictures with picture-circle type | Round thumbnails and preview. |
| Complete control over file list | External list and deletion veto. |
| Drag and Drop | drop and local list. |
| Paste | paste files from document for Upload and UploadDragger; disabled blocks processing. |
| Upload directory | Folder selection, drop with attachment bypass, relative paths and accept. |
| Upload manually | Manual local start from original review. |
| Upload png file only | Type checking and UPLOAD_LIST_IGNORE. |
| Pictures with list style | Thumbnail next to the name. |
| Customize preview file | Your own previewFile for text files. |
| Max Count | Replacement of one and limit of several files. |
| Transform file before request | Blob from beforeUpload is passed to the transport. |
| Aliyun OSS | Requires signing application server and cloud configuration. customRequest is available, cloud integration is not added here. |
| Custom action icon and extra info | Visibility of actions, extra and snippets removeIcon/downloadIcon/previewIcon. |
| Drag sorting of uploadList | itemRender and managed fileList: native drag and drop and rearrange buttons. React dnd-kit is not used. |
| Crop image before uploading | Trim editor requires separate integration; not added to the page. |
| Customize Progress Bar | Line Progress with size, colors, steps, format and ARIA. Percent belongs to the file. |
| Custom semantic dom styling | Local and general classNames/styles for root/list/item/trigger, including callbacks. |
| Property | Description | Type | Default |
|---|---|---|---|
progress | Line Progress settings without type/percent. General and local parameters are combined by fields. Without general settings, any passed object, including {}, replaces the entire defaults Upload. size specifies the thickness; colors, format, steps, semantic slots and ARIA are related to Progress. The bar appears 300 ms after the mount line when uploading and the specified percent of the file. | UploadListProgressProps | { size: [-1, 2], showInfo: false } |
classNames | Classes root/list/item/trigger by object or callback from { props }. General and local classes accumulate. Root complements class and rootClassName; item refers to a regular string inside the file container. | UploadSemanticValue<T> | — |
styles | CSS lines of the same four slots or callback. Local ones are applied after general ones. styles.root styles the wrapper; trigger gets provider styles.trigger, provider style, local styles.trigger, local style in that order. Root variables are inherited by trigger. | UploadSemanticValue<T> | — |
directory | Folder selection and FileSystemEntry bypass when drop/paste. Attachments save webkitRelativePath to originFileObj. multiple remains a separate prop, accept is applied before beforeUpload. | boolean | false |
iconRender | The file icon gets the current listType and status. An empty snippet does not return fallback; the number 0 is displayed. The finished image thumbnail in picture views has priority. | Snippet<[UploadFile<T>, NonNullable<UploadProps["listType"]>]> | Standard icon |
itemRender | Your own line instead of originNode or around it. originNode - snippet with error Tooltip; actions contains preview/download/remove. The order of the fileList is set by the application, the disabled of its controls is also set explicitly. | Snippet<[Snippet, UploadFile<T>, readonly UploadFile<T>[], UploadItemRenderActions]> | Standard line |
pastable | Listen to paste files throughout ownerDocument. Text without files is not intercepted. multiple counts accept; single takes the first source file. Local/inherited disabled blocks insertion; UploadDragger inherits prop. | boolean | false |
prefixCls | Full CSS prefix of the component and its parts. A non-empty local prop takes precedence; empty string and undefined inherit ConfigProvider. The namespace of the topic is set separately. | string | ConfigProvider.prefixCls + "-upload" |
fileList | Managed list. Take info.fileList from onChange; bind:fileList is not supported. | readonly UploadFile<T>[] | Local list |
defaultFileList | Initial list if there is no fileList. | readonly UploadFile<T>[] | [] |
action | Address of this shipment. On this page the transport is local. | string | (file) => string | PromiseLike<string> | Empty string |
name | Multipart request field name. method supports POST, PUT and PATCH. | string | file |
data | Additional request fields; headers and withCredentials configure the HTTP transport. | object | (file) => object | PromiseLike<object> | {} |
beforeUpload | false or rejected Promise stops sending, keeping the file in the list. UPLOAD_LIST_IGNORE excludes it; Blob/File replaces the request content. | (file, batch) => void | boolean | string | Blob | PromiseLike<...> | — |
customRequest | Local handler takes precedence over ConfigProvider.upload.customRequest. The change applies to the following files; the current request is saved. The transport receives onProgress, onSuccess, onError and abort. defaultRequest allows you to use the original XHR implementation. | (options, { defaultRequest }) => UploadRequest | void | XHR |
onChange | Current file, list and progress information. If beforeUpload=false the file may not have status. | (info: UploadChangeParam<T>) => void | — |
onRemove | false disables deletion. Allowed deletion cancels an active file request. | (file) => void | boolean | PromiseLike<void | boolean> | Allowed |
accept | Local accept, including empty line, overrides ConfigProvider.upload.accept. Types for dialogue and filtering directory or multiple drop/paste. Filter:native disables checking in the code, callback sets its own filter. Perform application validation in beforeUpload. | string | { format, filter } | Empty string |
multiple | Select multiple files at once. directory preserves the prop and does not truncate the folder traversal based on this flag. | boolean | false |
maxCount | List limit; 1 replaces the previous file. | number | No limit |
listType | List and thumbnail view. | text | picture | picture-card | picture-circle | text |
showUploadList | Visibility of the list and actions, extra and snippets previewIcon/downloadIcon/removeIcon with the current file. Snippet changes the content of the control, not the predicate, name or callback. Empty does not hide control; undefined returns the default SVG. | boolean | UploadListOptions<T> | true |
previewFile | Returns the source of the thumbnail when originFileObj and thumbUrl === undefined. An empty thumbUrl disables generation and uses the url. isImageUrl determines the display of the image. | (file: File | Blob) => PromiseLike<string> | Image preview |
onPreview | Your preview; Image cards use Modal. | (file) => void | Go to URL |
onDownload | The application controls the download. The extra card only shows the received name. | (file) => void | Open URL |
onDrop | Drag event in UploadDragger/type=drag. | (event: DragEvent) => void | — |
disabled | Blocks selection, paste and drop processing, including the late result of folder traversal. Pass disabled to your children and controls from itemRender. | boolean | From Form/ConfigProvider |
openFileDialogOnClick | Allows click to open selection. hasControlInside=false enables role=button and the container's keyboard. | boolean | true |
locale | Labels of loading, deleting, downloading, viewing and errors. | UploadLocale | From ConfigProvider.locale |
inputElement | bind:inputElement returns hidden file input; bind:nativeElement - root span. | HTMLInputElement | — |
General settings Upload
UploadConfig sets in ConfigProvider.upload class/style, classNames/styles, accept, customRequest and progress. A missing nested record inherits the parent one, the passed object replaces it entirely. An empty object removes the entire upload-record, preserving other provider settings.
General and local classes are accumulated. For root/list/item, the general slots CSS lines come before the local ones; for trigger the order is: general styles.trigger, general style, local styles.trigger, local style. Local empty classNames/styles do not remove common ones. accept, including the empty string, and customRequest are fetched locally or from provider. Callback semantic slots receives the original local accept, not its inherited value.
Progress is merged on top of a common object by fields. The customRequest change applies to the following files; the running transport is saved. Example uses shared and local transport without a server, inherited Dragger and an empty nested record.
Standard action icons
UploadListOptions<T> accepts previewIcon, downloadIcon and removeIcon how Snippet<[UploadFile<T>]>. They replace the contents of controls; available names from locale, show*Icon, status/disabled and callbacks are preserved. Preview icon is used in picture-card/picture-circle, download - only when done. An empty snippet does not hide the control, undefined returns the standard icon, 0 is displayed.
Progress and semantic types
UploadListProgressProps sets linear Progress settings: size, showInfo, strokeColor, railColor, status/success, steps, format, semantic slots and ARIA. Percent belongs to the file. Without local and global progress, size=[-1,2] and showInfo=false are used. General and local parameters are combined by fields; local empty object does not clear provider progress. If there is no general progress, the passed object replaces the entire defaults Upload. Fields UploadFile['aria-label'] and ['aria-labelledby'] set the name of the band; progress props of the same name take precedence.
UploadSemanticSlots - partial record root/list/item/trigger with string values. UploadSemanticValue<T> accepts record or callback, returning record or undefined. UploadSemanticInfo<T> contains props with listType, type, multiple, hasControlInside, disabled and showUploadList enabled; other input settings, including local prefixCls, remain original; DOM bindings nativeElement/inputElement are excluded. The Callback should evaluate the decoration without changing the state.
Snippets lines and icons
iconRender(file, listType) replaces the file icon. itemRender(originNode, file, fileList, actions) replaces the line or supplements it: output the standard part via @render originNode(). originNode saves Tooltip errors, fileList contains current order.
Export UploadItemRenderActions describes download: () => void, preview: (event?: MouseEvent) => void and remove: () => void. Preview transfers the file to onPreview; when the event is transmitted and onPreview cancels the transition. Without onPreview he does not create his viewer. download calls onDownload or opens URL; remove goes through onRemove, including veto, and cancels the request if deletion is allowed. The visibility of disabled's own buttons is determined by the application.
Name link attributes
UploadFile.linkProps accepts HTMLAnchorAttributes | string: object of native Svelte attributes or their JSON. The default is target="_blank", rel="noopener noreferrer" and title=file.name; linkProps can override them. href is always taken from file.url. Attributes apply only to the name link with a url, not to the thumbnail, preview action or name button without a url.
Use native class, onclick and string style. onclick is called first; preventDefault skips onPreview. Return false and stopPropagation by themselves do not cancel preview. JSON does not pass the onclick function; an invalid line causes a SyntaxError. Example shows updating attributes and downloading local text without onPreview.
UploadDragger and file data
UploadDragger is a separate export with the same props and height for the drop area. It sets type="drag" and hasControlInside=false. UploadRcFile extends File with uid; UploadFile stores name, status, percent, originFileObj, response, error, url, thumbUrl, fileName, preview and linkProps. fileName is optional metadata; the label uses name. Preview is an application cache; thumbnails use thumbUrl/url. Read directory paths from originFileObj.webkitRelativePath; UploadFile has no separate path.
UploadFile.error accepts Error | ProgressEvent | { statusText?: string; message?: string }. When status="error" the Tooltip selects a non-empty string response, then error.statusText, error.message and locale.uploadError. Empty fields are ignored and the response object does not replace the message. Initial list shows the priority of statusText over message.
Full types are in the package. The new onFocus/onBlur from React 6.7.0 are not carried over; For native Svelte events, use the available HTML handlers. directory, pastable, iconRender and itemRender are supported by Upload and UploadDragger. ConfigProvider.upload specifies general Upload and UploadDragger settings; progress and semantic slots are supported locally and via provider.
Methods
UploadRef describes bind:this for Upload and UploadDragger: onBatchStart, onProgress, onSuccess, onError, fileList, upload, nativeElement and inputElement. UploadBatchFileInfo contains file and parsedFile; null leaves the record without uploading. Batch does not run beforeUpload or a transport.
onSuccess parses a JSON string; progress/success/error ignore removed uids. UploadUploaderRef.abort cancels a request without removing its row. After unmount, batch preparation neither publishes files nor starts a transport.
Upload and UploadDragger provide abort(file?) through bind:this - stopping all requests or one UploadFile/uid. The method does not change fileList by itself: basic example separately transfers canceled entries to error.
When Upload unmounts, it calls abort() on each pending request. Use bind:inputElement and bind:nativeElement to access the DOM. Upload has no separate focus() or blur() methods.
DOM and accessibility
The root span contains a hidden input type="file", trigger and a list. When hasControlInside=true, the action is performed by the nested native Button; disabled is passed to both components. UploadDragger makes the area a button with Enter and Space handling.
List actions have accessible names from locale. onPreview allows you to show a Modal instead of following a link. Thumbnails and previews in cards have an alt, and generated Object URLs are freed when replaced, deleted, or unmounted.
classNames/styles are designed in four parts. class and rootClassName add wrapper classes; regular style refers to trigger and takes precedence over styles.trigger. For trigger content, use children. extra complements the standard line, showUploadList controls the visibility of its actions. iconRender changes the icon, itemRender changes the contents of the line inside the file container. Keep accessible names and disabled names for your actions; Provide a keyboard-based alternative to drag-and-drop for sorting.
| Slot | Element | Purpose |
|---|---|---|
root | External span wrapper | Design of the entire area, including CSS variables for descendants. |
list | List Div | Visible when showUploadList; in picture-card/picture-circle also contains trigger. |
item | Standard file line | Inside list-item-container, including the error Tooltip line. When itemRender is applied only if the originNode is rendered. |
trigger | Selection Area or Dragger | External control, not hidden input. Regular style overrides styles.trigger. |
Registration tokens
theme.components.Upload sets actionsColor for regular list actions and pictureCardSize for picture-card/picture-circle. The settings also apply to UploadDragger. Actions on top of the image remain white. Updating the theme saves the list and current download. ConfigProvider.upload sets props/defaults separately from theme.components.Upload.
| Token | Purpose |
|---|---|
actionsColor | Normal list action color; actions on top of picture-card/picture-circle remain white. |
pictureCardSize | Square or round card size. |
Common tokens of the current topic
Values are read through theme.useToken() and react to section settings.
| Token | Current value |
|---|---|
colorBgMask | rgba(0,0,0,0.45) |
colorBorder | #d9d9d9 |
colorError | #ff4d4f |
colorFillAlter | rgba(0,0,0,0.02) |
colorIcon | rgba(0,0,0,0.45) |
colorPrimary | #2f54eb |
colorPrimaryBorder | #adc6ff |
colorPrimaryHover | #597ef7 |
colorText | rgba(0,0,0,0.88) |
colorTextDescription | rgba(0,0,0,0.45) |
colorTextDisabled | rgba(0,0,0,0.25) |
colorTextHeading | rgba(0,0,0,0.88) |
colorTextLightSolid | #fff |
borderRadiusLG | 8 |
borderRadiusSM | 4 |
controlItemBgHover | rgba(0,0,0,0.04) |
fontFamily | -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji' |
fontSize | 14 |
fontSizeHeading2 | 30 |
fontSizeHeading3 | 24 |
fontSizeLG | 16 |
lineHeight | 1.5714285714285714 |
lineType | solid |
lineWidth | 1 |
lineWidthFocus | 3 |
margin | 16 |
marginXL | 32 |
marginXS | 8 |
marginXXS | 4 |
motionDurationMid | 0.2s |
motionDurationSlow | 0.3s |
motionEaseInOut | cubic-bezier(0.645, 0.045, 0.355, 1) |
motionEaseInOutCirc | cubic-bezier(0.78, 0.14, 0.15, 0.86) |
padding | 16 |
paddingSM | 12 |
paddingXS | 8 |
FAQ
What is the difference between false and UPLOAD_LIST_IGNORE?
false cancels automatic sending, keeping the file in the list. UPLOAD_LIST_IGNORE excludes the entry completely; the constant is imported separately from @woodger/antd.
Why is the managed list not updating?
Accept info.fileList in onChange. Once you remove an entry from a managed list, do not return it from your transport's late response.
Where does the file error text come from?
When status='error' the standard Tooltip selects the first non-empty line: response, error.statusText, error.message, then locale.uploadError. Blank lines are skipped; the response object is not parsed as a message. UploadFile.error accepts Error, ProgressEvent or an object with string statusText/message. In initial list archive.zip has both fields set: Tooltip shows statusText.
How to download a file or show an image?
Fill in url and thumbUrl or process onDownload/onPreview. In the demos, actions are performed locally.
How to get the source file?
Read originFileObj. With beforeUpload=false, the callback can pass the original File directly; this is reflected in the public type UploadChangeParam.
Where is the server configured?
In action for standard XHR or in customRequest for your own transport. Selecting a file and displaying a list does not in itself create a server handler.
Why can I select an individual file instead of a folder in Safari?
directory and webkitdirectory set the intent for the browser, but do not guarantee the same dialog on all platforms. Limit the selection via accept.format and set accept.filter separately if necessary. Check the size and other application conditions in beforeUpload.
Why did the error or buttons disappear after replacing the line?
When completely replacing originNode, you are responsible for their output. Outputting originNode via @render preserves the default string and Tooltip; the passed actions allow you to link your controls to callbacks Upload. Pass these controls disabled and available names.
Why did progress={} change the height and show the percentage?
Without general progress, this is an explicit replacement for defaults Upload. If there is a provider progress, an empty local object stores its parameters. To get a thin strip without a signature, set size=[-1,2] and showInfo=false explicitly.
Why isn't styles.item styling my string?
Slot refers to the standard line. When itemRender outputs the originNode or style your markup inside the snippet. For an external area use root, for a list use list.
How are the thumbnail and preview source selected?
Example of sources shows the priority of a non-empty thumbUrl over a url. An empty thumbUrl uses the url and disables previewFile. Generation is called only when thumbUrl === undefined and originFileObj is present. Updating a reactive counter inside previewFile does not regenerate the thumbnail for the same file.
When does a deleted row disappear?
List Animations does not delay fileList updates, callbacks, or request cancellations. The line remains until the CSS animation completes or the 2000ms wait limit. Returning the same uid before leaving completes preserves the DOM. The initial files are not animated; theme.token.motion=false and prefers-reduced-motion complete the transition immediately. The picture-card/picture-circle trigger supports enter/leave, preserves its input and does not animate on initial appearance. Progress appearance animation is not available yet.
