Upload / UploadDragger
使用受控列表选择、拖放文件。
何时使用
上传选择文件并显示上传进度、结果和可用操作。 UploadDragger 添加了一个具有相同列表和传输契约的拖动区域。将它们用于附件、头像和图像集。
演示在本地处理文件:customRequest 模拟发送,手动脚本将其推迟到单击按钮。对于您的应用程序,指定服务器 action 或您自己的请求实现。
CSS 前缀 上传 显示全局 ConfigProvider.prefixCls 和本地 prefixCls,无需重置状态。触发器、列表和上传/拖动器状态遵循 prefixCls。 Button、Progress 和 Tooltip 分别继承公共前缀。这里是手动模式:文件选择不发送网络请求。
列出和预处理
FileList - 具有稳定 uid、名称、状态和进度的 UploadFile 数组。外部控制时,从每个 onChange 接受 info.fileList。 defaultFileList 指定初始条目,例如以前保存的附件。
| 问题 | 设置 | 示例 |
|---|---|---|
| 选择并发送文件 | customRequest、onChange |
点击下载 |
| 管理列表和删除 | fileList、onRemove |
管理列表 |
| 设置文件错误文本 | response、error.statusText、error.message、locale.uploadError |
初始名单 |
| 选择包含附件的文件夹 | directory、accept |
文件夹和附件 |
| 自定义名称链接 | UploadFile.linkProps |
链接属性 |
| 设置默认为全部上传 | ConfigProvider.upload | 常规设置 |
| 自定义操作图标 | showUploadList.*Icon |
图标和信息 |
| 配置加载栏 | progress、UploadFile.percent |
进度登记 |
列表和 trigger 的设计部分 |
classNames、styles |
Semantic DOM |
| 更改文件图标 | snippet iconRender |
你的图标 |
| 重新排列文件并更改行 | itemRender、fileList |
自有线路及订单 |
| 从缓冲区接收文件 | pastable、beforeUpload |
插入文件 |
| 排除不适当的文件 | beforeUpload, UPLOAD_LIST_IGNORE |
仅限PNG |
| 发货前更换车身 | 返回的斑点 | 请求前转换 |
| 延迟发送 | beforeUpload={() => false} |
手动下载开始 |
beforeUpload=false 停止自动上传,但将文件保留在列表中,而没有所需的 status。被拒绝的 Promise 也会停止请求。单独导入的常量 UPLOAD_LIST_IGNORE 完全消除了该条目。处理程序返回的 Blob 替换请求的正文;源文件保存在模型中。
pastable 可以从Upload和UploadDragger的缓冲区中粘贴文件;默认为 false。处理程序侦听整个文档:关注相邻字段不会限制加载。常规文本插入仍然是原生的。每个带有 pastable 的活动上传都会收到一个事件,因此在具有多个加载器的页面上,仅针对您需要的加载器启用它。disabled,包括 ConfigProvider,阻止插入。离开页面时,订阅将被删除。
插入的文件会经历与选择和 drop 相同的 beforeUpload、fileList 驱动的传输。具有 multiple paste/drop 功能,按 accept 进行过滤;在单个文件中,第一个源文件是在过滤之前获取的。在 beforeUpload 中单独检查强制限制。 例子 启动时禁用插入,在本地保存文件,并允许您在没有网络的情况下切换到 Dragger 或本地 customRequest。
directory 将 directory/webkitdirectory添加到文件输入中。该对话框选择一个文件夹,drop/paste 绕过嵌套的 FileSystemEntry 并将相对路径保存到 originFileObj.webkitRelativePath。遍历读取 directory 阅读器的所有部分;不可用的条目将被跳过。 multiple 仍然是一个单独的 prop,并且不将遍历限制为单个文件。disabled 或离开页面时,最新阅读结果不包含在列表中。
directory accept 在 beforeUpload 之前应用,包括对话框选择。带有 filter 的对象:'native' 将检查留给浏览器;回调 filter 设置自己的检查。当 drop/paste 依赖于浏览器时支持选择文件夹和条目:如果条目不可用,爬网不会从常规文件中恢复它们。服务器上的结构由您的传输决定,而不是 fileList。
accept 指定可用的选择格式; beforeUpload 适用于检查大小和应用条件。 multiple 允许多个文件,maxCount 限制列表;如果 maxCount=1,则新文件替换旧文件。从托管模型中删除的条目不再接收状态更新:保持列表最新以获取最新的传输响应。
请求、进度和取消
标准发送使用XHR:action 指定URL,name 是文件字段的名称,method是HTTP方法。data、标头和 withCredentials 传递请求参数。可以针对特定文件异步计算 action 和 data。
customRequest 接收文件、action、文件名、方法、data、标头和 onProgress/onSuccess/onError 回调。通过 onProgress 报告百分比并使用最后两个处理程序之一终止请求。 info.defaultRequest 允许您调用原始 XHR 实现,而不是完全重复传输。
让 customRequest 返回一个带有 abort() 方法的对象,在该方法中停止请求并释放资源。Upload 卸载时会为每个未完成的请求调用这个方法。即使 customRequest 在返回对象之前就关闭了表单,这些请求也会被取消。
若要用按钮取消上传,可通过 bind:this 获取 Upload 实例。调用 abort(file) 可停止一个请求,调用 abort() 可停止所有进行中的请求。在基础示例中,按钮还会更新受控 fileList 中已取消文件的状态。
onRemove 可以返回 false 或带有 false 的 Promise 以防止移除;被拒绝的 Promise 也会保存记录。如果允许删除,则活动发送将被取消。 指导示例 分别显示禁止删除和 disabled。
列表视图和操作
listType 选择 text、图片、picture-card 或 picture-circle。 图像墙和圆形版本使用相同型号。 Url指定文件链接,thumbUrl 指定缩略图; previewFile 允许您异步准备图像。
如果有 url,linkProps 设置文件名链接的属性:HTMLAnchorAttributes 对象或 JSON。使用的是Nativeclass、onclick 和stringstyle。 target、rel、title、download、aria-* 和 data-* 可以明确指定; href 始终取自 file.url。属性不适用于缩略图、单独的预览 action 或没有 URL 的名称。
onclick 在 onPreview 之前调用。 event.preventDefault() 取消 preview,返回 false,而 stopPropagation() 则不会。 JSON 只传输可序列化的属性;无效的行会引发 SyntaxError。在示例中,您可以禁用 onPreview 并通过 download 下载本地文本。
showUploadList 配置 preview/remove/download 和片段 extra 的可见性。 Snippets previewIcon/downloadIcon/removeIcon 接收文件并更改常规操作的内容。显示图标、locale 的名称、状态、disabled 和回调均被保留。预览图标用于卡片/circle,download - 仅用于完成。空代码片段不会隐藏 control:为此,请设置 showicon; undefined 返回标准 SVG,显示 0。 onPreview 和 onDownload 将操作传递给应用程序:演示打开本地 Modal 或显示文件名。应用程序在替换或删除图像以及卸载时创建的自由对象 URL。
children 设置拖动器按钮或内容的 Svelte 片段。也将 disabled 传递给子按钮,以便其外观和可访问性与上传一致。 mount后可以使用 bind:inputElement 和 bind:nativeElement;没有单独的 focus/blur。
iconRender - 带有文件和当前 listType 的精简代码片段。它替换了图标,包括上传状态。空片段会留下没有后备空间的空间;显示数字 0。图片视图中的完成图像缩略图仍然是优先考虑的。
itemRender 获取 originNode、文件、当前 readonly fileList 和操作。 originNode 通过 @render originNode() 渲染,并包含标准错误工具提示行。您可以补充它或完全替换它。空片段会使外部文件容器为空;undefined 返回默认字符串。
UploadItemRenderActions 类型描述了 preview(event?)、download() 和 remove()。他们调用回调Upload;remove 可以保存否决权 onRemove 并取消请求。如果 onPreview 存在,则取消传递的预览 MouseEvent;如果没有回调,该操作不会自动打开查看器。自定义按钮不会继承操作的 disabled 和可见性:显式设置它们。在下载示例中,它仅显示文件名。
该顺序由应用程序的 fileList 数组确定。该示例将本机拖放与可访问的上方/下方按钮相结合;稳定的 uid 由注释编辑器保存。 itemRender 本身不对数据进行排序,也不包含 React dnd-kit。
Progress 配置线性文件栏:现有 Progress 的 size、showInfo、颜色/渐变、status/success、步骤、格式、语义槽和 ARIA。type 和百分比不包含在对象中:百分比存储在 UploadFile 中并由传输通过 onProgress 更新。对于厚度使用 size。仅当上传并指定百分比时,该条才会在挂载线后 300 毫秒出现;对于 SSR,它还不存在。
没有局部和总体 progress,则使用 size=[-1,2] 和 showInfo=false。全局和本地参数按字段组合:本地空对象存储提供程序 progress。如果没有一般 progress,则传递的对象(包括空对象)将替换默认的 Upload;缺少的字段接收默认进度。可用的名称可以使用 UploadFile 的 aria-label/aria-labelledby 字段设置;progress 道具优先。如果未指定名称,本地化文本将与文件名一起存储。
classNames/styles 的样式为 root、list、item 和触发器。 classNames 指定类、styles – CSS 字符串;两者都接受来自 { props } 的记录或回调。回调看到 listType、type、multiple、hasControlInside、disabled 和 showUploadList 启用,其他输入设置保持原来的。 DOM 绑定 nativeElement/inputElement 不会传递给回调。不要更改回调内的状态。
Root - 外部包装器 span,list - 列表容器,item - 文件容器内的常规行,trigger - 选择区域或拖动器,不隐藏输入。如果 itemRender 完全替换 originNode,则不会渲染 item 槽。 class 和 rootClassName 补充 classNames.root; styles.root 应用于 wrapper 及其变量。常规 style 引用 trigger 并覆盖 styles.trigger。进度设置有自己的语义槽。
ConfigProvider.upload 指定上传和拖动器的 class/styles、classNames/style、accept、customRequest 和 progress。没有上传的嵌套提供者继承记录;传输的上传完全取代了它。空对象仅清除上传记录,不会清除主题和其他设置。
总体设计和局部设计的课程都会累积。通用插槽的 CSS 行位于本地插槽之前;对于 trigger,顺序是:常规 styles.trigger,常规 style,局部 styles.trigger,局部 style。本地空类名/样式不会覆盖全局 classNames/styles。回调接收的是原始的本地 accept,而不是继承的值。空的本地 accept 会删除通用过滤器;检查文件的有效性仍然是 beforeUpload 任务。
本地 customRequest 优先于通用请求。更改处理程序会影响以下文件,保存正在运行的请求和列表。该示例将保留请求,直到按下按钮为止,并显示通过卸载取消不完整的请求;在具有空记录的区域中,beforeUpload 返回 false,以便不运行标准 XHR。
组件上传设计令牌(design tokens)有效,并且与组件配置分开设置。 API 中列出了支持的设置。
Ref 与文件元数据
生命周期方法 通过 bind:this 展示 Upload 和 UploadDragger 的 UploadRef。onBatchStart 接收包含 file 和 parsedFile 的 UploadBatchFileInfo[]:null 保留文件,但不进入 uploading 状态。它不执行 beforeUpload 或传输。onProgress、onSuccess 和 onError 仅在 uid 仍存在于当前列表时更新记录;onSuccess 解析 JSON 响应字符串。
FileList、upload、nativeElement 和 inputElement 从当前 ref 读取。UploadUploaderRef 提供 abort(file?),用于取消请求但不删除行。卸载后,batch 准备过程既不会发布记录,也不会启动传输。
在照片墙中,fileName 保存可选元数据,应用使用 preview 作为缓存。行标签仍使用 name;缩略图使用 thumbUrl/url。达到限制时,children=undefined 隐藏选择区域,同时保留隐藏 input 以供下次选择。
示例
添加和删除行
四种类型的列表,返回相同的 uid 并禁用运动。型号列表立即更改,注册单独完成。
<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>{("列表视图 ")}<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}>{("显示选择区域")}</Checkbox></p>
<p><Checkbox bind:checked={motion}>{("列出动画")}</Checkbox></p>
<p>
<Button onclick={() => {
const id = nextId++; files = [...files, {
...initial,
uid: `added-${id}`,
name: `logo-${id}.webp`
}];
}}>{("添加准备好的文件")}</Button>
<Button onclick={() => { files = files.filter(file => file.uid !== initial.uid); }}>
{("删除源文件")}
</Button>
<Button onclick={() => {
if (!files.some(file => file.uid === initial.uid)) {
files = [initial, ...files];
}
}}>{("恢复原始文件")}</Button>
</p>
{#snippet trigger()}<Button>{("选择动画示例文件")}</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={("模型文件")}>{(files.map(file => file.name).join(', ')
|| ("空列表"))}</output></p>
<p>
{("模型立即更新;删除的行将保留到动画结束。在完成之前返回相同的 uid 会保存字符串。初始文件没有动画显示;考虑系统运动减少设置。")}
</p>
空的thumbUrl会通过url保存图像和预览,但会禁用previewFile的生成。生成器需要 originFileObj 和thumbUrl === 未定义。非空的thumbUrl 优先。
缩略图和预览源
空的 thumbUrl 使用不生成的url;非空优先。如果 undefined 并且使用了 originFileObj,则调用 previewFile。
<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>{("缩略图视图 ")}<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>{("缩略图来源 ")}<select bind:value={mode}>
<option value="empty">{("空的thumbUrl:使用url")}</option>
<option value="custom">{("非空thumbUrl:自定义缩略图")}</option>
<option value="generated">{("未设置thumbUrl:调用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}</output></p>
<p>
{("空的thumbUrl会通过url保存图像和预览,但会禁用previewFile的生成。生成器需要 originFileObj 和thumbUrl === 未定义。非空的thumbUrl 优先。")}
</p>
<Modal
open={Boolean(preview)}
title={("预览源码")}
footer={null}
onCancel={() => { preview = ''; }}
>
{#if preview}<img
src={preview}
alt={("选定的来源")}
style="
display: block;
max-width: 100%;
margin: auto;
"
/>{/if}
</Modal>
点击下载
本地 customRequest 显示进度和完成情况。以 .fail 结尾的名称显示错误。删除或中止会取消计时器;向服务器发出的请求未得到满足。
<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(("演示下载错误")));
}
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(("下载已取消")) }
: file);
}
</script>
<style>
output { overflow-wrap: anywhere; }
</style>
<Upload
bind:this={control}
fileList={(files)}
multiple
customRequest={request}
onChange={info => { files = info.fileList; }}
>
<Button>{("选择文件")}</Button>
</Upload>
<p><Button
disabled={!files.some(file => file.status === 'uploading')}
onclick={handleAbort}
>{("取消请求")}</Button></p>
<p><output aria-label={("下载状态")}>{(files.map(
file => `${file.name}: ${file.status ?? 'pending'} (${file.percent ?? 0}%)`
).join('; ') || ("未选择文件"))}</output></p>
头像选择
beforeUpload 检查最多 1MB 的 PNG/JPEG。 false 停止发送,保留本地预览。对象 URL 在替换和卸载时被释放。
<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 = ("选择大小不超过 1 MB 的 PNG 或 JPEG。");
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={("选择头像")}>
{#if image}
<img src={image} alt={("选定的头像")} />
{:else}
<span>
{("+ 头像")}
</span>
{/if}
</button>
</Upload>
<p><output aria-label={("头像文件")}>{((error || name)
|| ("未选择头像"))}</output></p>
初始文件列表
defaultFileList 指定就绪状态完成、上传和 error。指向 archive.zip:error.statusText 优先于 error.message。 beforeUpload=false 允许您添加文件而不自动上传。
<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: "服务器拒绝存档", message: "加载失败" }
}
];
</script>
<Upload defaultFileList={(initial)} beforeUpload={() => false}>
<Button>{("添加到开始列表")}</Button>
</Upload>
<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={("添加图像")}><span aria-hidden="true">+</span>{("添加")}</button>
{/snippet}
<Modal
open={Boolean(preview)}
title={("图片预览")}
footer={null}
onCancel={() => { preview = ''; }}
>
{#if preview}<img
class="preview"
src={preview}
alt={("选定的图像")}
/>{/if}
</Modal>
圆形图像
listType="picture-circle" 更改缩略图的形状。由于 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={("添加圆形图像")}
>+</button>
</Upload>
<Modal
open={Boolean(preview)}
title={("文件预览")}
footer={null}
onCancel={closePreview}
>
{#if preview}<img
class="preview"
src={preview}
alt={("图片预览")}
/>{/if}
</Modal>
<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} />{(" 允许删除策略")}</label>
</p>
<Upload fileList={(files)} beforeUpload={() => false} onChange={info => {
files = info.fileList;
}}
onRemove={file => file.uid !== 'keep' || canRemove}>
<Button>{("添加文档")}</Button>
</Upload>
<p>
<Button onclick={() => { files = files.filter(file => file.uid !== 'draft'); }}>
{("删除草稿")}
</Button>
</p>
<p><output aria-label={("托管文件")}>{(files.map(file => file.name).join(', ')
|| ("空列表"))}</output></p>
单击或拖动文件
文件将保留在本地列表中。
拖放文件
UploadDragger 通过选择和 drop 来接受文件。 onDrop 接收事件; beforeUpload=false 将文件保存在本地。
<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">{("单击或拖动文件")}</p>
<p class="ant-upload-hint">{("文件将保留在本地列表中。")}</p>
</UploadDragger>
<p><output
aria-label={("结果下降")}
>Drop: {dropped}{(";文件: ")}{(files.length)}</output></p>
仅限PNG
accept 限制对话框中的选择,beforeUpload 检查类型。 UPLOAD_LIST_IGNORE 从列表中排除被拒绝的文件; false 不发送则保持有效。
<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 = ("该文件不是 PNG。");
return UPLOAD_LIST_IGNORE;
}
message = ("PNG 已接受但未发送。");
return false;
}
</script>
<Upload
fileList={(files)}
accept="image/png"
beforeUpload={validate}
onChange={info => { files = info.fileList; }}
>
<Button>{("选择PNG")}</Button>
</Upload>
<p><output aria-label={("PNG检查")}>{(message
|| ("选择一个 PNG 文件"))}</output></p>
<p><output aria-label={("接受的 PNG")}>{(files.map(file => file.name).join(', ')
|| ("列表为空"))}</output></p>
启用粘贴,复制文件或图像并按 Ctrl+V 或 ⌘V。该处理程序作用于整个文档,包括当焦点位于下面的注释字段时。纯文本继续插入到字段中。
默认情况下,beforeUpload=false 将文件保留在本地。如果清除此标志,customRequest 仅确认本地结果,而不进行网络请求。多次使用接受;在单个粘贴/放置中,在过滤之前获取第一个源文件。在beforeUpload中单独指定文件有效性检查。
从缓冲区插入文件
pastable 用于Upload 和UploadDragger:paste 文档处理、multiple/accept、beforeUpload、本地 customRequest 和 disabled。显式启用插入;文件不会发送到服务器。
<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(("下载旁边注意"));
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 || "无类型"})`);
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}>{("启用文件插入")}</Checkbox>
<Checkbox bind:checked={dragger}>{("通过UploadDragger插入")}</Checkbox>
<Checkbox bind:checked={multiple}>{("缓冲区中的多个文件")}</Checkbox>
<Checkbox bind:checked={textOnly}>{("插入时接受 .txt")}</Checkbox>
<Checkbox
bind:checked={manual}
>{("保留插入的文件而不发送")}</Checkbox>
<Checkbox
bind:checked={localDisabled}
>{("本地阻止插入")}</Checkbox>
<Checkbox
bind:checked={providerDisabled}
>{("通过提供商进行块插入")}</Checkbox>
</div>
<p>
{("启用粘贴,复制文件或图像并按 Ctrl+V 或 ⌘V。该处理程序作用于整个文档,包括当焦点位于下面的注释字段时。纯文本继续插入到字段中。")}
</p>
<TextArea
aria-label={("文件插入旁边的注释")}
bind:value={draft}
rows={3}
/>
<ConfigProvider componentDisabled={providerDisabled}>
{#if dragger}
<UploadDragger {...props} bind:nativeElement={root} bind:inputElement={input}>
<p>{("单击、拖动或粘贴剪贴板中的文件")}</p>
</UploadDragger>
{:else}
<Upload {...props} bind:nativeElement={root} bind:inputElement={input}>
<Button disabled={localDisabled ? true : undefined}>
{("选择要插入的文件")}
</Button>
</Upload>
{/if}
</ConfigProvider>
<output aria-label={("插入的文件列表")}>
{(files.map(file => `${file.name}: ${file.status ?? "不发送"}`).join('; ')
|| ("空的"))}
</output>
<output aria-label={("检查插入的文件")}>{(checked.join('; ')
|| ("没有支票"))}</output>
<output aria-label={("批量插入文件")}>{(batches.join(' | ')
|| ("禁止举办派对"))}</output>
<output aria-label={("本地插入查询")}>{(requests.join(', ')
|| ("没有要求"))}</output>
<output
aria-label={("粘贴列表事件")}
>{("变化: ")}{changes}</output>
<output aria-label={("上传插入的根源")}>{(root && input ? "已连接" : "等待挂载")}</output>
<p>
{("默认情况下,beforeUpload=false 将文件保留在本地。如果清除此标志,customRequest 仅确认本地结果,而不进行网络请求。多次使用接受;在单个粘贴/放置中,在过滤之前获取第一个源文件。在beforeUpload中单独指定文件有效性检查。")}
</p>
</div>
单击或拖动包含文本文件的文件夹
目录包括文件夹选择和删除时的附件旁路。路径是从originFileObj.webkitRelativePath中读取的;文件夹结构不会自动发送到服务器。 BeforeUpload 返回 false:文件保留在本地。
在文件夹模式下,接受过滤器.txt到beforeUpload。 “信任接受对话框”设置过滤器:'native'并在代码中禁用此过滤。多个仍然是一个单独的属性:目录不会自动启用它,并且不会截断单个文件的附件。
选择文件夹和附件
Upload和Dragger中的 directory,相对路径,multiple 并 accept。通过本机对话框选择文件夹或传输到区域; beforeUpload 将文件保留在本地。
<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}>{("选择整个文件夹")}</Checkbox>
<Checkbox bind:checked={dragger}>{("通过 UploadDragger 的文件夹")}</Checkbox>
<Checkbox bind:checked={multiple}>{("选择文件夹时有多个")}</Checkbox>
<Checkbox bind:checked={nativeFilter}>{("信任接受对话")}</Checkbox>
<Checkbox bind:checked={disabled}>{("块文件夹选择")}</Checkbox>
</div>
{#if dragger}
<UploadDragger {...props} bind:nativeElement={root} bind:inputElement={input}>
<p>{("单击或拖动包含文本文件的文件夹")}</p>
</UploadDragger>
{:else}
<Upload {...props} bind:nativeElement={root} bind:inputElement={input}>
<Button {disabled}>{("选择包含文本文件的文件夹")}</Button>
</Upload>
{/if}
<output aria-label={("文件夹文件路径")}>
{(files.map(file => file.originFileObj?.webkitRelativePath || file.name).join('; ')
|| ("未选择文件夹"))}
</output>
<output aria-label={("批处理文件夹")}>{(batches.join(' | ')
|| ("没有支票"))}</output>
<output aria-label={("文件夹选择的根源")}>{(root && input ? "已连接" : "等待挂载")}</output>
<p>
{("目录包括文件夹选择和删除时的附件旁路。路径是从originFileObj.webkitRelativePath中读取的;文件夹结构不会自动发送到服务器。 BeforeUpload 返回 false:文件保留在本地。")}
</p>
<p>
{("在文件夹模式下,接受过滤器.txt到beforeUpload。 “信任接受对话框”设置过滤器:'native'并在代码中禁用此过滤。多个仍然是一个单独的属性:目录不会自动启用它,并且不会截断单个文件的附件。")}
</p>
</div>
IconRender获取当前文件和列表类型,包括上传状态。空片段不会返回默认图标;显示数字 0。图片视图中的完成图像优先于图标。
给出初始状态用于比较。新文件保留在本地:beforeUpload 返回 false。
自定义文件图标
iconRender as Svelte 片段,带有文件/listType:状态、空结果、数字 0 和图片视图中已完成缩略图的优先级。
<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: "本地文件错误" },
{ 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={("图标 " + String((file.name)) + ": " + String((currentType)) + ": " + String((file.status ?? ("当地的"))) + "")}>
{(file.name.endsWith('.png') ? 'PNG' : 'TXT')}
</span>
{/if}
{/snippet}
<div class="example">
<div class="controls">
<label>{("具有自己的图标的列表视图\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>{("绘制文件图标\n ")}<select bind:value={mode}>
<option
value="custom"
>{("自己的图标")}</option><option
value="default"
>{("常规的")}</option>
<option
value="empty"
>{("空片段")}</option><option
value="zero"
>{("号码 0")}</option>
</select>
</label>
<Checkbox bind:checked={thumbnail}>{("成品缩略图封面.png")}</Checkbox>
</div>
<Upload {listType} fileList={(displayed)} iconRender={mode === 'default'
? undefined
: fileIcon}
beforeUpload={() => false} onChange={info => { files = info.fileList; }}>
<Button>{("添加带有您自己的图标的文件")}</Button>
</Upload>
<p>
{("IconRender获取当前文件和列表类型,包括上传状态。空片段不会返回默认图标;显示数字 0。图片视图中的完成图像优先于图标。")}
</p>
<p>
{("给出初始状态用于比较。新文件保留在本地:beforeUpload 返回 false。")}
</p>
</div>
位置 1 从 3
位置 2 从 3
位置 3 从 3
拖动线条或使用“上方”和“下方”。顺序由应用程序的fileList决定;持久 uid 保留该行及其注释。 OriginNode - 带有工具提示错误的标准行片段。
动作调用回调上传;禁用,其按钮的可用性由应用程序确定。 Policy.txt 通过 onRemove 进行保护。这里下载只显示名称;不发送新文件。
自己的线路和文件顺序
itemRender 获取 originNode、文件、当前列表和操作。通过拖放或按钮排序可以保存笔记;查看、下载和否决删除与回调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: "本地错误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((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 ?? "当地的")}</p>{/if}
<p>{("位置 ")}{(fileList.findIndex(item => item.uid === file.uid) + 1)}{(" 从 ")}{(fileList.length)}</p>
<label class="editor">{("备注 ")}{file.name}
<Input bind:value={notes[file.uid]} {disabled} />
</label>
<div class="actions">
<Button
{disabled}
aria-label={("看法 " + String((file.name)) + "")}
onclick={actions.preview}
>{("看法")}</Button>
<Button {disabled} aria-label={("下载 " + String((file.name)) + "")} onclick={actions
.download}>{("下载")}</Button>
<Button {disabled} aria-label={("删除 " + String((file.name)) + "")} onclick={actions
.remove}>{("删除")}</Button>
<Button disabled={disabled || firstFile?.uid === file.uid}
aria-label={("更高 " + String((file.name)) + "")} onclick={() => {
const uid = file.uid;
const index = fileList.findIndex(item => item.uid === uid);
move(uid, index - 1);
}}>{("更高")}</Button>
<Button disabled={disabled || lastFile?.uid === file.uid}
aria-label={("以下 " + String((file.name)) + "")} onclick={() => {
const uid = file.uid;
const index = fileList.findIndex(item => item.uid === uid);
move(uid, index + 1);
}}>{("以下")}</Button>
</div>
</section>
{/snippet}
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("自定义列表行上传")}</Checkbox>
<Checkbox bind:checked={origin}>{("保存originNode")}</Checkbox>
<Checkbox bind:checked={disabled}>{("锁定你的线路")}</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 ? ("已删除") : ("禁止拆除"))) + ": " + String((file.name)) + "");
return allowed;
}}>
<Button {disabled}>{("将文件添加到您的列表中")}</Button>
</Upload>
<output aria-label={("订购您的清单")}>{(files.map(
file => file.name
).join(', ')
|| ("空的"))}</output>
<output aria-label={("下载你的字符串")}>{(downloaded
|| ("没有下载"))}</output>
<output aria-label={("删除自己的行")}>{(removed
|| ("没有删除"))}</output>
<p>
{("拖动线条或使用“上方”和“下方”。顺序由应用程序的fileList决定;持久 uid 保留该行及其注释。 OriginNode - 带有工具提示错误的标准行片段。")}
</p>
<p>
{("动作调用回调上传;禁用,其按钮的可用性由应用程序确定。 Policy.txt 通过 onRemove 进行保护。这里下载只显示名称;不发送新文件。")}
</p>
</div>
<Modal open={Boolean(preview)} title={("您的线路详细信息")} footer={null}
onCancel={() => { preview = ''; }}>
<p>{preview}</p>
</Modal>
LinkProps 更改名称的链接属性。 Href 始终取自 file.url。如果没有 url,则不会应用链接属性;缩略图和单独的预览按钮也不会收到它们。
Onclick 在 onPreview 之前执行。 PreventDefault 取消预览,返回 false,而 stopPropagation 则不会。 JSON传递属性,无需onclick函数;无效的 JSON 会引发语法错误。要下载本地文本示例,请关闭 onPreview 并保留 return false 处理程序。
文件名链接属性
UploadFile.linkProps 作为对象或 JSON:class、style、download、可用名称和 onclick。顺序是 onclick/onPreview、preventDefault、no url 和本地文本的本机下载。
<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(("请注意链接旁边的内容"));
let preview = $state('');
let events = $state<string[]>([]);
const url = '/examples/upload/notes.txt';
const attributes: HTMLAnchorAttributes = {
target: '_self',
rel: 'noopener',
title: "文字示例上传",
download: 'notes.txt',
href: '#link-props-ignored',
class: 'upload-demo-filename',
style: 'font-weight:600',
'aria-label': "下载示例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}>{("JSON 格式的 LinkProps")}</Checkbox>
<Checkbox bind:checked={hasUrl}>{("发送文件网址")}</Checkbox>
<Checkbox bind:checked={withPreview}>{("将名称与 onPreview 关联")}</Checkbox>
<label>{("名称引用处理程序\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={("文件链接旁边的注释")} bind:value={draft} />
<Upload
fileList={([file])}
showUploadList={({ showRemoveIcon: false })}
onPreview={withPreview ? current => {
events.push('preview');
preview = current.name;
} : undefined}
/>
<output aria-label={("链接事件的顺序")}>{(events.join(' → ')
|| ("没有活动"))}</output>
<p>
{("LinkProps 更改名称的链接属性。 Href 始终取自 file.url。如果没有 url,则不会应用链接属性;缩略图和单独的预览按钮也不会收到它们。")}
</p>
<p>
{("Onclick 在 onPreview 之前执行。 PreventDefault 取消预览,返回 false,而 stopPropagation 则不会。 JSON传递属性,无需onclick函数;无效的 JSON 会引发语法错误。要下载本地文本示例,请关闭 onPreview 并保留 return false 处理程序。")}
</p>
</div>
<Modal open={Boolean(preview)} title={("文件链接信息")} footer={null}
onCancel={() => { preview = ''; }}>
<p>{preview}</p>
</Modal>
列表中的图像
图片显示文件名旁边的缩略图。初始数据和添加的图像使用相同的列表。
<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>{("将图像添加到列表")}</Button>
</Upload>
<Modal
open={Boolean(preview)}
title={("文件预览")}
footer={null}
onCancel={closePreview}
>
{#if preview}<img
class="preview"
src={preview}
alt={("图片预览")}
/>{/if}
</Modal>
您自己的文件缩略图
previewFile 返回一个包含缩略图来源的 Promise。在示例中,文本文件接收通用 SVG 缩略图;该文件未传输到服务器。
<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>{("添加带有缩略图的文本")}</Button>
</Upload>
<Modal open={preview} title={("文件缩略图")} footer={null} onCancel={() => {
preview = false;
}}>
<img
src={thumbnail}
alt={("文本文件的总体草图")}
style="
display: block;
max-width: 100%;
margin: auto;
"
/>
</Modal>
一个文件
最多三个文件
数量限制
maxCount=1 替换以前的文件。在 multiple 文件中,列表仅限于三个文件。
<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>{("一个文件")}</p><Upload
maxCount={1}
beforeUpload={() => false}
><Button>{("选择一个文件")}</Button></Upload></div>
<div><p>{("最多三个文件")}</p><Upload
maxCount={3}
multiple
beforeUpload={() => false}
><Button>{("最多选择三个文件")}</Button></Upload></div>
</div>
请求前转换
beforeUpload 返回一个 Blob,其标题位于原始文本之前。 customRequest 读取转换后的字节并验证本地结果。
<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>{("转换文本")}</Button>
</Upload>
<pre><output aria-label={("准备好的请求体")}>{(body
|| ("尚未选择文字"))}</output></pre>
列出操作和附加信息
showUploadList 控制每个文件操作的可见性,extra 添加信息。操作图标在以下示例中单独显示。
<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)}{(" 字节")}</small>
{/snippet}
<Upload defaultFileList={(initial)} beforeUpload={() => false}
showUploadList={({
extra,
showRemoveIcon: file => file.uid !== 'locked',
showDownloadIcon: true
})}
onDownload={file => { downloaded = file.name; }}>
<Button>{("添加信息文件")}</Button>
</Upload>
<p><output aria-label={("请求文件上传")}>{(downloaded
|| ("未请求加载"))}</output></p>
片段接收当前文件并更改标准操作的内容。空代码片段为控件留下了可访问的名称;要隐藏,请使用 show*Icon。预览显示在卡片/圆圈中,下载 - 仅用于完成。禁用的块删除、查看和下载仍然可用。
这里的回调显示文件名; Draft.svg 通过 onRemove 进行保护。未定义返回默认图标,显示数字0。新文件保留在本地而不发送。
操作图标和详细信息
片段 previewIcon/downloadIcon/removeIcon 获取文件。可见性、可用名称和回调仍然是标准的;比较自己的图标、空图标和标准图标。
<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(("图标旁边的注释"));
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)}{(" 字节")}</small>
{/snippet}
<div class="example">
<div class="controls">
<label>{("上传操作图标\n ")}<select bind:value={mode}>
<option value="custom">
{("他们的")}
</option>
<option value="default">
{("常规的")}
</option>
<option
value="empty"
>{("空片段")}</option>
<option
value="zero"
>{("号码 0")}</option>
</select>
</label>
<label>{("包含操作的列表视图\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}>{("禁用下载和删除")}</Checkbox>
<Checkbox bind:checked={onlyMap}>{("仅下载map.svg")}</Checkbox>
</div>
<Input aria-label={("操作图标旁边的注释")} 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 ? ("已删除") : ("禁止拆除"))) + ": " + String((file.name)) + "");
return allowed;
}}>
<Button {disabled}>{("添加")}</Button>
</Upload>
<output aria-label={("通过您的图标下载")}>{(downloaded
|| ("没有下载"))}</output>
<output aria-label={("通过您的图标删除")}>{(removed
|| ("没有删除"))}</output>
<output aria-label={("带有操作图标的文件")}>{(files.map(file => file.name)
.join(', ')
|| ("空的"))}</output>
<p>
{("片段接收当前文件并更改标准操作的内容。空代码片段为控件留下了可访问的名称;要隐藏,请使用 show*Icon。预览显示在卡片/圆圈中,下载 - 仅用于完成。禁用的块删除、查看和下载仍然可用。")}
</p>
<p>
{("这里的回调显示文件名; Draft.svg 通过 onRemove 进行保护。未定义返回默认图标,显示数字0。新文件保留在本地而不发送。")}
</p>
</div>
<Modal open={Boolean(preview)} title={("上传操作详情")} footer={null}
onCancel={() => { preview = ''; }}>
<p>{preview}</p>
</Modal>
常规和本地设置
继承的拖拽者
空嵌套记录
Sample.txt - 42% 的样本条。新文件在本地处理:单击“结束请求”。在重置范围内,beforeUpload 返回 false 以避免运行标准 XHR。
空上传继承整个记录;空的嵌套记录将替换它。类是累积的,局部 CSS 行在通用 CSS 行之后应用。进度跨字段合并:一个空的本地对象存储总体进度。更改customRequest会影响以下文件,当前请求继续;隐藏上传会取消不完整的上传。
常规设置上传
ConfigProvider.upload:继承、记录重置、本地样式/accept、progress 合并和传输选择。更改设置时会保存未完成的请求,卸载时会取消未完成的请求。
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(("提供者旁边的注释")); 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} >{("第一次上传的本地customRequest")}</Checkbox> <Checkbox bind:checked={localStyles} >{("第一次上传的本地样式")}</Checkbox> <Checkbox bind:checked={clearAccept}>{("空本地接受")}</Checkbox> <Checkbox bind:checked={wide}>{("提高整体进度")}</Checkbox> <Checkbox bind:checked={mounted}>{("显示带有设置的上传")}</Checkbox> <label>{("第一次上传的本地进度\n ")}<select bind:value={progressMode} > <option value="inherit" >{("继承")}</option> <option value="empty" >{("空物体")}</option> <option value="hide"> {("无签名")} </option> <option value="thick"> {("厚度 9 像素")} </option> </select> </label> </div> <Input aria-label={("注意 ConfigProvider.upload 旁边的内容")} bind:value={draft} /> <ConfigProvider upload={shared}> {#if mounted} <div class="scopes"> <ProviderUploadScope id="local" title={("常规和本地设置")} overrides={local} /> <ConfigProvider> <ProviderUploadScope id="inherited" title={("继承的拖拽者")} dragger /> </ConfigProvider> <ConfigProvider upload={{}}> <ProviderUploadScope id="reset" title={("空嵌套记录")} manual /> </ConfigProvider> </div> {/if} </ConfigProvider> <Button disabled={pending.length === 0} onclick={complete} >{("结束请求")}</Button> <output aria-label={("ConfigProvider.上传请求")}>{(requests.join('; ') || ("没有要求"))}</output> <output aria-label={("待处理的上传请求")} >{("期待: ")}{(pending.length)}</output> <output aria-label={("已取消的上传请求")}>{(aborted.join('; ') || ("不可取消"))}</output> <p> {("Sample.txt - 42% 的样本条。新文件在本地处理:单击“结束请求”。在重置范围内,beforeUpload 返回 false 以避免运行标准 XHR。")} </p> <p> {("空上传继承整个记录;空的嵌套记录将替换它。类是累积的,局部 CSS 行在通用 CSS 行之后应用。进度跨字段合并:一个空的本地对象存储总体进度。更改customRequest会影响以下文件,当前请求继续;隐藏上传会取消不完整的上传。")} </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': `进度示例: ${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>{("单击或拖动文件")}</p> </UploadDragger> {:else} <Upload {...overrides} fileList={(files)} bind:nativeElement={root} bind:inputElement={input} beforeUpload={() => manual ? false : undefined} onChange={info => { files = info.fileList; }}> <Button>{("选择文件")}</Button> </Upload> {/if} </div> <output aria-label={("文件: " + String((title)) + "")}> {files.map(file => `${file.name}: ${file.status ?? "不发送"}`).join('; ')} </output> <output aria-label={("DOM: " + String((title)) + "")}>{(root && input ? "已连接" : "等待挂载")}</output> </section>
<script lang="ts">
import { Button, Upload } from '@woodger/antd';
let disabled = $state(true);
</script>
<p><label><input
type="checkbox"
bind:checked={disabled}
/>{(" 阻止上传")}</label></p>
<Upload {disabled} beforeUpload={() => false}>
<Button {disabled}>{("选择可用文件")}</Button>
</Upload>
这里的百分比和状态是手动设置的,无需请求。在应用程序中,百分比是从 onProgress 更新的。仅当 status='uploading' 且指定百分比时,该栏才会出现在挂载线之后,并延迟 300 毫秒。
如果没有本地和总体进度,Upload 设置 size=[-1,2] 和 showInfo=false。通用参数和局部参数按字段组合。如果没有共同进度,任意对象替换默认上传;缺少的字段接收默认进度。要更改厚度,请使用尺寸。名称可以设置为UploadFile,进度优先。
文件进度设计
作为线条设置对象的进度:大小、颜色、渐变、步骤、格式和可用名称。百分比存储在 UploadFile 中;缺少 prop 和空对象会给出不同的默认值。
<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(("请注意进度旁边的内容"));
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}转移百分比`
}
};
const selected = presets[mode];
return commonLabel
? { ...selected, 'aria-label': "整体进度上传" }
: selected;
});
const file = $derived<UploadFile>({
uid: 'transfer',
name: 'archive.zip',
status: uploading ? 'uploading' : 'done',
percent: hasPercent ? percent : undefined,
'aria-label': "传输存档.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>{("上传进度设计\n ")}<select bind:value={mode}>
<option
value="default"
>{("没有进展")}</option>
<option
value="empty"
>{("空物体")}</option>
<option
value="color"
>{("颜色和厚度")}</option>
<option
value="gradient"
>{("坡度")}</option>
<option value="steps">
{("步骤")}
</option>
<option value="format">
{("你自己的格式")}
</option>
</select>
</label>
<label>{("带进度的列表视图\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}>{("文件正在加载")}</Checkbox>
<Checkbox bind:checked={hasPercent}>{("传输文件的百分比")}</Checkbox>
<Checkbox
bind:checked={commonLabel}
>{("进度名称与文件名重叠")}</Checkbox>
</div>
<Slider
aria-label={("文件上传百分比")}
bind:value={percent}
min={0}
max={100}
/>
<Input aria-label={("请注意上传进度旁边")} bind:value={draft} />
<div class="transfer">
<Upload {listType} {progress} fileList={([file])} showUploadList={({
showRemoveIcon: false
})} />
</div>
<output
aria-label={("上传进度状态")}
>{(file.status)}: {(file.percent ?? "没有百分比")}</output>
<p>
{("这里的百分比和状态是手动设置的,无需请求。在应用程序中,百分比是从 onProgress 更新的。仅当 status='uploading' 且指定百分比时,该栏才会出现在挂载线之后,并延迟 300 毫秒。")}
</p>
<p>
{("如果没有本地和总体进度,Upload 设置 size=[-1,2] 和 showInfo=false。通用参数和局部参数按字段组合。如果没有共同进度,任意对象替换默认上传;缺少的字段接收默认进度。要更改厚度,请使用尺寸。名称可以设置为UploadFile,进度优先。")}
</p>
</div>
Root 是一个包装器,list 是一个列表,item 是一个标准字符串,trigger 是一个选择区域或拖动器。 Class 和 rootClassName 补充 classNames.root。 CSS样式应用到相关部分;常规样式会覆盖 styles.trigger。
回调接收当前上下文中启用的默认值和禁用属性。在这里,它在禁用时更改行高。当通过 itemRender 完全替换 originNode 时,项目槽不会显示。新文件保存在本地,而不发送。
列表和选择区域的语义 DOM
Root/list/item/trigger 通过 classNames 和 CSS styles 行:对象、回调、拖动器和普通 style 的优先级。更改设计时会保存文件和外部编辑器。
<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(("设计旁边的注释"));
let files = $state.raw<UploadFile[]>([
{ uid: 'report', name: 'report.txt', status: 'done' },
{ uid: 'draft', name: 'draft.txt', status: 'error', response: "字符串格式错误" }
]);
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>{("语义设置上传\n ")}<select bind:value={mode}>
<option
value="object"
>{("目的")}</option><option
value="callback"
>Callback</option>
<option value="empty">{("空设置")}</option>
</select>
</label>
<label>{("格式化列表视图\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}>{("语义设计拖动器")}</Checkbox>
<Checkbox bind:checked={disabled}>{("禁用已发布的上传")}</Checkbox>
<Checkbox
bind:checked={priority}
>{("常规样式位于 styles.trigger 之上")}</Checkbox>
</div>
<Input aria-label={("上传设计旁边的注释")} bind:value={draft} />
{#if dragger}
<UploadDragger {...props} bind:nativeElement={root} bind:inputElement={input}>
<p>{("单击或拖动文件到设计区域")}</p>
</UploadDragger>
{:else}
<Upload {...props} bind:nativeElement={root} bind:inputElement={input}>
<Button {disabled}>{("添加文件")}</Button>
</Upload>
{/if}
<output aria-label={("上传文件")}>{(files.map(file => file.name)
.join(', ')
|| ("空的"))}</output>
<output aria-label={("设计上传的根源")}>{(root && input ? "已连接" : "等待挂载")}</output>
<p>
{("Root 是一个包装器,list 是一个列表,item 是一个标准字符串,trigger 是一个选择区域或拖动器。 Class 和 rootClassName 补充 classNames.root。 CSS样式应用到相关部分;常规样式会覆盖 styles.trigger。")}
</p>
<p>
{("回调接收当前上下文中启用的默认值和禁用属性。在这里,它在禁用时更改行高。当通过 itemRender 完全替换 originNode 时,项目槽不会显示。新文件保存在本地,而不发送。")}
</p>
</div>
组件主题上传
常规列表操作颜色和卡片大小、UploadDragger 和主题在本地上传期间发生变化。对服务器的请求未得到满足。
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( ("演示错误") ) } ]; 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}>{("应用上传令牌")}</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={("将文件添加到主题卡")}> <span aria-hidden="true">+</span>{("添加\n ")}</button> </Upload> <UploadDragger class="theme-dragger" defaultFileList={(documents)} beforeUpload={() => false} > <p class="ant-upload-text">{("单击或拖动文件")}</p> <p class="ant-upload-hint">{("该文件将保留在本地列表中。")}</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(("演示下载错误"))); } 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(("下载已取消")) } : file); } </script> <style> output { overflow-wrap: anywhere; } </style> <Upload bind:this={control} fileList={(files)} multiple customRequest={request} onChange={info => { files = info.fileList; }} > <Button>{("选择文件")}</Button> </Upload> <p><Button disabled={!files.some(file => file.status === 'uploading')} onclick={handleAbort} >{("取消请求")}</Button></p> <p><output aria-label={("下载状态")}>{(files.map( file => `${file.name}: ${file.status ?? 'pending'} (${file.percent ?? 0}%)` ).join('; ') || ("未选择文件"))}</output></p>
单击或拖动文件
选择多个文件并手动开始下载。
该演示在本地运行,无需将文件发送到服务器。
手动下载开始
原始UploadDragger来自评论:列表,单独启动本地演示下载和重置。文件不会发送到服务器。
<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">{("单击或拖动文件")}</p>
<p class="ant-upload-hint">
{("选择多个文件并手动开始下载。")}
</p>
</UploadDragger>
<p>{("该演示在本地运行,无需将文件发送到服务器。")}</p>
<div style="
display: flex;
gap: 8px;
flex-wrap: wrap;
">
<Button type="primary" disabled={!files.length} loading={sending} onclick={send}>
{("开始演示下载")}
</Button>
<Button
onclick={() => {
generation++;
files = [];
result = '';
sending = false;
}}
>{("重置文件")}</Button>
</div>
<output aria-label={("上传的文件")}>{result}</output>
</div>
触发器、列表和上传/拖动器状态遵循 prefixCls。 Button、Progress 和 Tooltip 分别继承公共前缀。这里是手动模式:文件选择不发送网络请求。
CSS 前缀 上传
通用命名空间ConfigProvider和本地 prefixCls;当名称更改时,组件的状态将被保留。
<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}>{("通用前缀上传套件")}</Checkbox>
<Checkbox bind:checked={local}>{("本地前缀上传")}</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>{("选择带有前缀的文件")}</Button>
</Upload>
<UploadDragger prefixCls={localPrefix} beforeUpload={() => false}>
{("\n 拖放带有前缀的文件\n ")}
</UploadDragger>
<output
aria-label={("上传带有前缀的文件")}
>{("文件: ")}{(fileList.length)}</output>
</div>
</ConfigProvider>
<output
aria-label={("CSS 前缀上传")}
>{("一般的: ")}{prefix}{(";当地的: ")}{(localPrefix
|| ("来自提供商"))}</output>
<p>
{("触发器、列表和上传/拖动器状态遵循 prefixCls。 Button、Progress 和 Tooltip 分别继承公共前缀。这里是手动模式:文件选择不发送网络请求。")}
</p>
</div>
这些方法无需传输即可更新本地列表。onSuccess 解析 JSON;已删除 uid 的回调会被忽略。Abort 取消请求,但不会删除文件。
Upload 生命周期方法
Upload 和 UploadDragger 的 UploadRef:无需网络请求的 batch、进度、JSON 响应和错误。
<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>{("选择本地文件")}</p>
</UploadDragger>
{:else}
<Upload bind:this={control} fileList={files} beforeUpload={() => false} onChange={info => {
files = info.fileList;
}} hasControlInside>
<Button>{("选择本地文件")}</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(("本地示例错误")),
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>
{("这些方法无需传输即可更新本地列表。onSuccess 解析 JSON;已删除 uid 的回调会被忽略。Abort 取消请求,但不会删除文件。")}
</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
映射到 ant.design 上的 21 个上传实时页面主题。这里有 26 张卡片,其中包含有效的 Svelte 示例;明确列出了缺少的参数和单个应用程序集成。
| 主题 | 示例或限制 |
|---|---|
| Upload by clicking | 本地交通有进展、错误和取消。 |
| Avatar | 检查 PNG/JPEG 和本地图像。 |
| Default Files | 初始完成/上传/error。 |
| Pictures Wall | 管理墙、微型模型和模态。 |
| Pictures with picture-circle type | 圆形缩略图和预览。 |
| Complete control over file list | 外部名单和否决删除。 |
| Drag and Drop | drop 和本地列表。 |
| Paste | 从 Upload 和 UploadDragger 的文档中 paste 文件;disabled 块处理。 |
| Upload directory | 文件夹选择,通过绕过附件、相对路径进行 drop 并 accept。 |
| Upload manually | 从源代码审查中手动本地启动。 |
| Upload png file only | 类型检查和 UPLOAD_LIST_IGNORE。 |
| Pictures with list style | 名称旁边的缩略图。 |
| Customize preview file | 您自己的文本文件 previewFile。 |
| Max Count | 替换一个文件并限制多个文件。 |
| Transform file before request | beforeUpload 中的 Blob 被传递到传输。 |
| Aliyun OSS | 需要签名应用程序服务器和云配置。 customRequest 可用,这里不添加云集成。 |
| Custom action icon and extra info | 操作、extra 内容和片段的可见性 removeIcon/downloadIcon/previewIcon。 |
| Drag sorting of uploadList | itemRender 和托管 fileList:本机拖放和随机播放按钮。未使用 React dnd-kit。 |
| Crop image before uploading | 作物编辑器需要单独集成;未添加到页面。 |
| Customize Progress Bar | 线条进度,包括 size、颜色、步长、格式和 ARIA。百分比属于该文件。 |
| Custom semantic dom styling | root/list/item/trigger 的本地和共享 classNames/styles,包括回调。 |
| 属性 | 描述 | 类型 | 默认 |
|---|---|---|---|
progress | 没有 type/百分比的线路进度设置。通用参数和局部参数按字段组合。如果没有常规设置,任何传递的对象(包括 {})都会替换整个默认的 Upload。size 指定厚度;颜色、格式、步骤、语义槽和 ARIA 与进度相关。上传时,该栏会在挂载线后 300 毫秒以及文件的指定百分比出现。 | UploadListProgressProps | { size: [-1, 2], showInfo: false } |
classNames | 通过对象或来自 { props } 的回调来分类 root/list/item/trigger。普通班和地方班累计。 Root 补充了 class 和 rootClassName; item 指的是文件容器内的常规字符串。 | UploadSemanticValue<T> | — |
styles | 相同的四个插槽或回调的 CSS 行。局部的先应用一般的。 styles.root 为包装器设置样式;触发器按顺序获取提供程序 styles.trigger、提供程序 style、本地 styles.trigger、本地 style。根变量由触发器继承。 | UploadSemanticValue<T> | — |
directory | 选择文件夹并在 drop/paste 时绕过 FileSystemEntry。附件将 webkitRelativePath 保存到 originFileObj。 multiple 仍然是一个单独的 prop,accept 在 beforeUpload 之前应用。 | boolean | false |
iconRender | 文件图标获取当前的 listType 和 status。空片段不会返回后备;显示数字 0。图片视图中的成品图像缩略图优先。 | Snippet<[UploadFile<T>, NonNullable<UploadProps["listType"]>]> | 标准图标 |
itemRender | 您自己的线而不是 originNode 或其周围。 originNode - 带有错误工具提示的片段;操作包含 preview/download/remove。fileList 的顺序由应用程序设置,其控件的 disabled 也是明确设置的。 | Snippet<[Snippet, UploadFile<T>, readonly UploadFile<T>[], UploadItemRenderActions]> | 标准线 |
pastable | 收听整个 ownerDocument 中的 paste 文件。没有文件的文本不会被拦截。accept multiple 次计数; single 获取第一个源文件。本地/继承 disabled 块插入; UploadDragger 继承 prop. | boolean | false |
prefixCls | 组件及其部件的完整 CSS 前缀。非空本地 prop 优先;空字符串和 undefined 继承ConfigProvider。主题的命名空间是单独设置的。 | string | ConfigProvider.prefixCls + "-upload" |
fileList | 托管列表。从 onChange 中获取 info.fileList;不支持 bind:fileList。 | readonly UploadFile<T>[] | 本地列表 |
defaultFileList | 如果没有 fileList,则初始列表。 | readonly UploadFile<T>[] | [] |
action | 实际送货地址。在此页面上,交通是本地的。 | string | (file) => string | PromiseLike<string> | 空字符串 |
name | 多部分请求字段名称。方法支持 POST、PUT 和 PATCH。 | string | file |
data | 附加请求字段; headers 和 withCredentials 配置 HTTP 传输。 | object | (file) => object | PromiseLike<object> | {} |
beforeUpload | false 或被拒绝的 Promise 停止发送,并将文件保留在列表中。 UPLOAD_LIST_IGNORE 排除它; Blob/File 替换请求内容。 | (file, batch) => void | boolean | string | Blob | PromiseLike<...> | — |
customRequest | 本地处理程序优先于 ConfigProvider.upload.customRequest。该更改适用于以下文件;当前请求已保存。传输接收 onProgress、onSuccess、onError 和 abort。 defaultRequest 允许您使用原始的 XHR 实现。 | (options, { defaultRequest }) => UploadRequest | void | XHR |
onChange | 当前文件、列表和进度信息。如果 beforeUpload=false 文件可能没有 status。 | (info: UploadChangeParam<T>) => void | — |
onRemove | false 禁用删除。允许删除会取消活动文件请求。 | (file) => void | boolean | PromiseLike<void | boolean> | 允许 |
accept | 本地 accept(包括空行)会覆盖 ConfigProvider.upload.accept。用于对话和过滤 directory 或 multiple drop/paste 的类型。 Filter:native 禁用检查代码,回调设置自己的过滤器。在 beforeUpload 中执行应用程序验证。 | string | { format, filter } | 空字符串 |
multiple | 一次选择多个文件。 directory 保留该属性,并且不会根据此标志截断文件夹遍历。 | boolean | false |
maxCount | 列表限制; 1 替换之前的文件。 | number | 无限制 |
listType | 列表和缩略图视图。 | text | picture | picture-card | picture-circle | text |
showUploadList | 列表和操作、extra 和片段 previewIcon/downloadIcon/removeIcon 与当前文件的可见性。代码片段更改 control 的内容,而不是谓词、名称或回调。空并不会隐藏控件; undefined 返回默认的 SVG。 | boolean | UploadListOptions<T> | true |
previewFile | 当 originFileObj 和 thumbUrl === undefined 时,返回缩略图的来源。空的 thumbUrl 会禁用生成并使用url。 isImageUrl 决定图像的显示。 | (file: File | Blob) => PromiseLike<string> | 图片预览 |
onPreview | 您的预览;图像卡使用 Modal。 | (file) => void | 转到网址 |
onDownload | 该应用程序管理下载。extra 的卡片仅显示收到的姓名。 | (file) => void | 打开网址 |
onDrop | UploadDragger/type=drag 中的拖动事件。 | (event: DragEvent) => void | — |
disabled | 阻止选择、paste 和 drop 处理,包括文件夹遍历的最新结果。从 itemRender 将 disabled 传递给您的 children 和控件。 | boolean | 来自表单/ConfigProvider |
openFileDialogOnClick | 允许通过单击打开选择。 hasControlInside=false 启用 role=button 和容器的键盘。 | boolean | true |
locale | 上传、删除、下载、查看和错误签名。 | UploadLocale | 来自 ConfigProvider.locale |
inputElement | bind:inputElement 返回隐藏文件输入; bind:nativeElement - 根 span。 | HTMLInputElement | — |
常规设置上传
UploadConfig 设置在 ConfigProvider.upload class/style、classNames/styles、accept、customRequest 和 progress。缺失的嵌套记录继承父记录,传递的对象将其完全替换。空对象会删除整个上传记录,保留其他提供程序设置。
普通班和地方班累计。对于 root/list/item,通用插槽 CSS 行位于本地 CSS 行之前;对于 trigger,顺序是:常规 styles.trigger,常规 style,局部 styles.trigger,局部 style。本地空 classNames/styles 不会删除常见的。 accept(包括空字符串)和 customRequest 是在本地或从提供者获取的。回调语义槽接收原始本地 accept,而不是其继承值。
进度通过字段合并到公共对象之上。 customRequest 更改适用于以下文件;正在运行的传输被保存。 例子 使用共享和本地传输,无需服务器、继承的 Dragger 和空嵌套记录。
标准操作图标
UploadListOptions<T> 接受 previewIcon, downloadIcon 和 removeIcon 如何 Snippet<[UploadFile<T>]>。它们取代了控件的内容;保留来自 locale、show*icon、status/disabled 和回调的可用名称。预览图标用于 picture-card/picture-circle,仅在完成后 download。空代码片段不会隐藏 control,undefined 返回标准图标,显示 0。
进度和语义类型
UploadListProgressProps 设置线性进度设置:size、showInfo、strokeColor、railColor、status/success、步骤、格式、语义槽和 ARIA。百分比属于该文件。如果没有本地和全局 progress,则使用 size=[-1,2] 和 showInfo=false。通用参数和局部参数按字段组合;本地空对象不会清除提供程序 progress。如果没有总体 progress,则传递的对象将替换整个默认的上传。领域 UploadFile['aria-label'] 和 ['aria-labelledby'] 设置条带的名称;同名的 progress 道具优先。
UploadSemanticSlots — 带有字符串值的部分记录 root/list/item/trigger。 UploadSemanticValue<T> 接受记录或回调返回记录或 undefined。 UploadSemanticInfo<T> 包含 listType、type、multiple、hasControlInside、disabled 和 showUploadList 启用的道具;其他输入设置,包括本地 prefixCls,保持原始状态; DOM 绑定 nativeElement/inputElement 被排除。回调应该评估装饰而不改变状态。
片段线和图标
iconRender(file, listType) 替换文件图标。 itemRender(originNode, file, fileList, actions) 替换一行或补充它:通过输出常规部分 @render originNode()。 originNode 保存 Tooltip 错误,fileList 包含当前顺序。
出口 UploadItemRenderActions 描述 download: () => void, preview: (event?: MouseEvent) => void 和 remove: () => void。 Preview 将文件传递给 onPreview;当事件传递且 onPreview 取消转换时。如果没有 onPreview,它不会创建其查看器。download 调用 onDownload 或者打开URL; remove 会经历 onRemove,包括否决,如果允许删除,则取消请求。本机按钮的可见性和 disabled 由应用程序决定。
名称链接属性
UploadFile.linkProps 接受 HTMLAnchorAttributes | string:本机 Svelte 属性或其 JSON 的对象。默认为 target="_blank",rel="noopener noreferrer" 和 title=file.name; linkProps 可以覆盖它们。 href 始终取自 file.url。属性仅适用于带有 url 的名称链接,不适用于没有 url 的缩略图、preview action 或名称按钮。
使用原生 class, onclick 和字符串 style。首先调用 onclick; preventDefault 会跳过 onPreview。返回 false 和 stopPropagation 本身不会取消预览。 JSON 不传递 onclick 函数;无效行会导致 SyntaxError。 例子 显示更新属性和下载本地文本而不使用 onPreview。
UploadDragger和文件数据
UploadDragger 是独立导出,具有相同参数,并通过 height 设置拖放区域高度。它设置 type="drag" 和 hasControlInside=false。UploadRcFile 在 File 上扩展 uid;UploadFile 保存 name、status、percent、originFileObj、response、error、url、thumbUrl、fileName、preview 和 linkProps。fileName 是可选元数据;标签仍使用 name。Preview 是应用缓存;缩略图使用 thumbUrl/url。目录相对路径请读取 originFileObj.webkitRelativePath;UploadFile 没有单独的 path。
UploadFile.error 接受 Error | ProgressEvent | { statusText?: string; message?: string }。当 status="error" 时,工具提示选择非空字符串响应,然后选择 error.statusText、error.message 和 locale.uploadError。空字段将被忽略,响应对象不会替换消息。 初始名单 显示 statusText 相对于消息的优先级。
完整的类型都在包中。 React 6.7.0 中新的 onFocus/onBlur 不会被继承;对于本机 Svelte 事件,请使用可用的 HTML 处理程序。 Upload 和 UploadDragger 支持 directory、pastable、iconRender 和 itemRender。 ConfigProvider.upload指定常规Upload和UploadDragger设置;本地和通过 provider 支持 progress 和语义槽。
方法
UploadRef 描述 Upload 和 UploadDragger 的 bind:this:onBatchStart、onProgress、onSuccess、onError、fileList、upload、nativeElement 和 inputElement。UploadBatchFileInfo 包含 file 和 parsedFile;null 使记录不进入 uploading 状态。Batch 不执行 beforeUpload 或传输。
onSuccess 解析 JSON 字符串;progress/success/error 忽略已删除的 uid。UploadUploaderRef.abort 取消请求但不删除行。卸载后,batch 准备过程既不会发布文件,也不会启动传输。
Upload 和UploadDragger 通过 bind:this 提供 abort(file?) - 停止所有请求或一个 UploadFile/uid。该方法本身不会更改 fileList: 基本示例 单独将取消的条目转移到 error。
Upload 卸载时会调用每个未完成请求的 abort() 方法。 可通过 bind:inputElement 和 bind:nativeElement 访问 DOM。Upload 没有单独的 focus() 或 blur() 方法。
DOM 和可访问性
根 span 包含隐藏的输入 type="file"、trigger 和列表。当 hasControlInside=true 时,动作由嵌套的原生Button执行;disabled 被传递给两个组件。 UploadDragger 使该区域成为一个带有 Enter 和 Space 处理的按钮。
列表操作具有来自 locale 的可访问名称。 onPreview 允许您显示模态框而不是点击链接。卡片中的缩略图和预览具有 alt,并且生成的对象 URL 在替换、删除或卸载时会被释放。
classNames/styles 由四个部分组成。 class 和 rootClassName 添加包装类;常规 style 引用 trigger 并优先于 styles.trigger。对于触发内容,请使用 children。 extra 补充了标准线,showUploadList 控制其操作的可见性。 iconRender 更改图标,itemRender 更改文件容器内行的内容。为您的操作保留可访问的名称和 disabled 的名称;提供基于键盘的拖放排序替代方案。
| Slot | 元素 | 目的 |
|---|---|---|
root | 外 span 包覆 | 设置整个区域的样式,包括儿童的 CSS 变量。 |
list | 列表分区 | showUploadList 时可见;picture-card/picture-circle 中也包含触发器。 |
item | 标准锉线 | 在列表项容器内,包括错误工具提示行。仅当渲染 originNode 时才应用 itemRender。 |
trigger | 选择区域或拖动器 | 外部 control,非隐藏输入。常规 style 会覆盖 styles.trigger。 |
注册令牌
theme.components.Upload 设置常规列表操作的 actionsColor 和 picture-card/picture-circle 的 pictureCardSize。这些设置也适用于 UploadDragger。图像顶部的动作保持白色。更新主题会保存列表和当前下载。 ConfigProvider.upload 与 theme.components.Upload 分开设置 props/defaults。
| 代币 | 目的 |
|---|---|
actionsColor | 常规列表动作颜色;picture-card/picture-circle 顶部的动作保持白色。 |
pictureCardSize | 方形或圆形卡片尺寸。 |
当前主题的常用标记
这些值通过 theme.useToken() 读取并对部分设置做出反应。
| 代币 | 当前值 |
|---|---|
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
false 与 UPLOAD_LIST_IGNORE 有何不同?
false 取消自动发送,将文件保留在列表中。 UPLOAD_LIST_IGNORE 完全排除该条目;该常量是从 @woodger/antd 单独导入的。
为什么托管列表不更新?
在 onChange 中接受 info.fileList。从托管列表中删除条目后,请勿从传输的延迟响应中返回该条目。
文件错误文本从何而来?
当 status='error' 时,标准工具提示选择第一个非空行:response、error.statusText、error.message,然后是 locale.uploadError。空白行被跳过;响应对象不会被解析为消息。 UploadFile.error 接受 Error、ProgressEvent 或带有字符串 statusText/message 的对象。在 初始清单 archive.zip 中设置了两个字段:工具提示显示 statusText。
如何下载文件或显示图像?
填写url和 thumbUrl 或者处理 onDownload/onPreview。在演示中,操作在本地执行。
如何获取源文件?
读取 originFileObj。 beforeUpload=false 时,回调可以直接传递原始 File;这反映在公共类型 UploadChangeParam 中。
服务器在哪里配置?
标准 XHR 使用 action 或用于您自己的传输的 customRequest 中。选择文件并显示列表本身并不创建服务器处理程序。
为什么我可以在 Safari 中选择单个文件而不是文件夹?
directory 和 webkitdirectory 设置浏览器的意图,但不保证所有平台上的对话框相同。通过 accept.format 限制选择,并在必要时单独设置 accept.filter。在 beforeUpload 中检查大小和其他申请条件。
为什么更换线路后错误或按钮消失了?
如果你完全替换了 originNode,你就要对它们的输出负责。通过@render输出 originNode 保留默认字符串和Tooltip;传递的操作允许您将控件链接到回调上传。传递这些控件的 disabled 和可用名称。
为什么 progress={} 改变高度并显示百分比?
如果没有总体 progress,这是默认上传的明确替代。如果存在提供者 progress,则空的本地对象存储其参数。要获得没有签名的细条,请显式设置 size=[-1,2] 和 showInfo=false。
为什么 styles.item 没有为我的字符串设置样式?
槽指的是标准线。当 itemRender 输出 originNode 或在片段内设置标记的样式时。对于外部区域,请使用 root,对于列表,请使用 list。 当点断言不太能很好地表达意图时,
缩略图和预览源是如何选择的?
来源示例 显示非空 thumbUrl 相对于url 的优先级。空的 thumbUrl 使用url并禁用 previewFile。仅当 thumbUrl ===undefined 且 originFileObj 存在时才调用生成。在 previewFile 中更新响应式计数器,不会为同一个文件重新生成缩略图。
删除的行什么时候消失?
列出动画 不会延迟 fileList 更新、回调或请求取消。该行将一直保留,直到 CSS 动画完成或达到 2000 毫秒的等待限制。在离开完成之前返回相同的 uid 会保留 DOM。初始文件没有动画; theme.token.motion=false 和 prefers-reduced-motion 立即完成转换。picture-card/picture-circle 触发器支持进入和离开动画,保留 input,首次出现时不播放动画。暂不支持进度条出现动画。
