Demos
How to import
<script lang="ts">
import { Upload } from '@fibrae/semi-ui-svelte';
</script>
Basic usage
The most basic usage is to place a Button in the trigger area; clicking it opens the file selection box, and the upload starts automatically after the selection is completed
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload action="https://api.semi.design/upload">
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>File name too long ellipsis
Customize the file name tooltip using the showTooltip property
When the type is boolean, control whether to show the tooltip
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload action="https://api.semi.design/upload" showTooltip={false}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Customize the popup through the ellipsisTooltip snippet, which receives content (the full file name) and trigger (the file name element, placed in the popup with {@render trigger()}); an object showTooltip configures the tooltip type and the props passed to it.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Tooltip, Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload action="https://api.semi.design/upload" showTooltip>
{#snippet ellipsisTooltip({ content: text, trigger })}
<Tooltip position="bottom">
{#snippet content()}{text}{/snippet}
{@render trigger()}
</Tooltip>
{/snippet}
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Add prompt text
Set a custom prompt text through the prompt slot. Set the slot position by promptPosition, optional left, right, bottom, the default is right
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type PromptPositionType } from '@fibrae/semi-ui-svelte';
const action = 'https://api.semi.design/upload';
const marginStyle: Partial<Record<PromptPositionType, string>> = {
left: 'margin-right: 10px',
right: 'margin-left: 10px',
};
const promptStyle = (pos: PromptPositionType) => `display: flex; align-items: center; color: var(--semi-color-text-2); height: 32px; ${marginStyle[pos] ?? ''}`;
const positions: PromptPositionType[] = ['right', 'left', 'bottom'];
</script>
{#each positions as pos, index (pos)}
{#if index}
<div style="margin-bottom: 12px; margin-top: 12px; border-bottom: 1px solid var(--semi-color-border)"></div>
{/if}
<Upload {action} promptPosition={pos}>
{#snippet prompt()}
<div style={promptStyle(pos)}>请上传资格认证材料</div>
{/snippet}
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>
{/each}When listType is picture, the reference object at promptPosition is the whole picture wall list
Code
<script lang="ts">
import { IconPlus } from '@fibrae/semi-icons-svelte';
import { Upload, type FileItem, type PromptPositionType } from '@fibrae/semi-ui-svelte';
const action = 'https://api.semi.design/upload';
const marginStyle: Partial<Record<PromptPositionType, string>> = {
right: 'margin-left: 10px',
};
const promptStyle = (pos: PromptPositionType) => `display: flex; align-items: center; color: var(--semi-color-text-2); height: 100%; ${marginStyle[pos] ?? ''}`;
const initialList = (): FileItem[] => [
{
uid: '1',
name: 'dy.jpeg',
status: 'success',
size: '130kb',
url: '/assets/placeholder/avatar-a.svg',
},
{
uid: '5',
name: 'resso.jpeg',
status: 'wait',
percent: 50,
size: '222kb',
url: '/assets/placeholder/avatar-b.svg',
},
];
const positions: PromptPositionType[] = ['right', 'bottom'];
</script>
{#each positions as pos, index (pos)}
{#if index}
<div style="margin-bottom: 12px; margin-top: 12px; border-bottom: 1px solid var(--semi-color-border)"></div>
{/if}
<Upload {action} fileList={initialList()} listType="picture" promptPosition={pos}>
{#snippet prompt()}
<div style={promptStyle(pos)}>请上传认证材料</div>
{/snippet}
<IconPlus aria-label="上传图片" size="extra-large" />
</Upload>
{/each}Click on the avatar to trigger upload
Code
<script lang="ts">
import { IconCamera } from '@fibrae/semi-icons-svelte';
import { Avatar, Toast, Upload } from '@fibrae/semi-ui-svelte';
let url = $state('/assets/placeholder/avatar-a.svg');
const onSuccess = () => {
Toast.success('头像更新成功');
url = '/assets/ttmoment.jpeg';
};
const maskStyle = 'background-color: var(--semi-color-overlay-bg); height: 100%; width: 100%; display: flex; align-items: center; justify-content: center; color: var(--semi-color-white)';
</script>
<Upload accept="image/*" action="https://api.semi.design/upload" class="avatar-upload" onError={() => Toast.error('上传失败')} {onSuccess} showUploadList={false}>
<!-- the avatar is the whole content of the upload button, so its alt names the button -->
<Avatar alt="上传头像" src={url} style="margin: 4px">
{#snippet hoverMask()}
<div style={maskStyle}>
<IconCamera />
</div>
{/snippet}
</Avatar>
</Upload>.avatar-upload .semi-upload-add {
border-radius: 50%; // Make sure that only the circle is clicked on the hot zone
}
Custom upload attributes
Custom upload attributes can be added by setting data, headers
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
// A data function is evaluated per upload, so time is the upload moment
const data = () => ({
role: 'ies',
time: new Date().getTime(),
});
const headers = {
'x-tt-semi': 'semi-upload',
};
</script>
<Upload action="https://api.semi.design/upload" {data} {headers}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Upload file type
The type of files uploaded can be restricted through the accept attribute (the native html attribute of input).
accept supports the following two types of strings:
- A collection of file extensions (recommended), such as .jpg, .png, etc.;
- MIME types collection of file types, please refer to MDN document
For example, only allowing users to upload PNG and PDF files, accept can be written like this: accept ='.pdf,.png' or accept ='application/pdf,image/png' (the MIME type of PNG and PDF Connect through ,).
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
const action = 'https://api.semi.design/upload';
const imageOnly = 'image/*';
const videoOnly = 'video/*';
const fileLimit = '.pdf,.png,.jpeg';
</script>
<Upload accept={imageOnly} {action} style="margin-bottom: 12px">
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
上传图片
</Button>
</Upload>
<Upload accept={videoOnly} {action} style="margin-bottom: 12px">
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
上传视频
</Button>
</Upload>
<Upload accept={fileLimit} {action}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
上传 PDF, PNG, JPEG
</Button>
</Upload>Upload folder
By passing in directory as true, all files in the folder can be uploaded
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload action="https://api.semi.design/upload" directory>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
上传文件夹
</Button>
</Upload>Select multiple files at once
You can select multiple files to upload at the same time by setting the multiple attribute.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload action="https://api.semi.design/upload" multiple>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Limit the total number of files
You can limit the maximum number of files that can be uploaded by setting the limit property. When limit is 1, always replace the current one with the latest upload, and onExceed will not be called
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type UploadOnChangeProps } from '@fibrae/semi-ui-svelte';
const limit = 1;
const onChange = (props: UploadOnChangeProps) => {
console.log(props.fileList);
};
</script>
<Upload action="https://api.semi.design/upload" {limit} {onChange}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传(最多{limit}项)
</Button>
</Upload>When the limit is reached, disable the trigger control rather than Upload, so uploaded files can still be removed.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Toast, Upload, type UploadOnChangeProps } from '@fibrae/semi-ui-svelte';
const limit = 2;
// Only the trigger button is disabled; Upload itself stays enabled so files can still be removed.
let disabled = $state(false);
const onChange = (props: UploadOnChangeProps) => {
disabled = props.fileList.length === limit;
};
</script>
<Upload action="https://api.semi.design/upload" {limit} {onChange} onExceed={() => Toast.warning(`最多只允许上传${limit}个文件`)}>
<Button {disabled} theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传(最多{limit}项)
</Button>
</Upload>In the photo wall mode, when the number of uploaded files is equal to the limit, the upload entry will be automatically hidden
Code
<script lang="ts">
import { IconPlus } from '@fibrae/semi-icons-svelte';
import { Toast, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const fileList: FileItem[] = [
{
uid: '1',
name: 'dyBag.png',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/root-web-sites/edit-bag.jpeg',
},
{
uid: '2',
name: 'dyBag2.jpeg',
status: 'success',
size: '222KB',
preview: true,
fileInstance: new File([new ArrayBuffer(2048)], 'dyBag2.jpeg', { type: 'image/png' }),
url: '/assets/root-web-sites/edit-bag.jpeg',
},
];
</script>
<Upload accept="image/*" action="https://api.semi.design/upload" {fileList} limit={2} listType="picture" onExceed={() => Toast.warning('最多只允许上传2个文件')}>
<IconPlus aria-label="上传图片" size="extra-large" />
</Upload>Limit upload file size
The upload file size limit can be customized through the maxSize and minSize properties, and you can pass onSizeError to be notified when the limit is exceeded.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Toast, Upload, type CustomFile } from '@fibrae/semi-ui-svelte';
const onSizeError = (file: CustomFile) => Toast.error(`${file.name} size invalid`);
</script>
<Upload action="https://api.semi.design/upload" maxSize={1024} minSize={200} {onSizeError}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传(最小 200KB,最大 1MB)
</Button>
</Upload>Custom list operation area
When listType is list, you can customize the list operation area through the fileOperation snippet, which receives UploadFileItemSlotProps

Code
<script lang="ts">
import { IconDelete, IconDownload, IconEyeOpened, IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const action = 'https://api.semi.design/upload';
const fileList: FileItem[] = [
{
uid: '1',
name: 'dyBag.png',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/root-web-sites/edit-bag.jpeg',
},
];
</script>
<Upload {action} {fileList} itemStyle="width: 300px">
{#snippet fileOperation({ onRemove })}
<div style="display: flex; column-gap: 8px; padding: 0 8px">
<Button aria-label="预览" size="small" theme="borderless" type="tertiary">
{#snippet icon()}<IconEyeOpened />{/snippet}
</Button>
<Button aria-label="下载" size="small" theme="borderless" type="tertiary">
{#snippet icon()}<IconDownload />{/snippet}
</Button>
<Button aria-label="删除" size="small" theme="borderless" type="tertiary" onclick={() => onRemove()}>
{#snippet icon()}<IconDelete />{/snippet}
</Button>
</div>
{/snippet}
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Custom file list title
When listType is list, you can customize the title area at the top of the file list through two snippets:
Replace only the title text
fileListTitle replaces only the title text, and the clear button retains its default style:
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const action = 'https://api.semi.design/upload';
const initialList = (): FileItem[] => [
{
uid: '1',
name: 'document.pdf',
status: 'success',
size: '130KB',
},
{
uid: '2',
name: 'report.xlsx',
status: 'success',
size: '222KB',
},
];
</script>
<Upload {action} fileList={initialList()} style="margin-bottom: 20px">
{#snippet fileListTitle()}已上传文件{/snippet}
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
自定义标题文字
</Button>
</Upload>
<Upload {action} fileList={initialList()}>
{#snippet fileListTitle()}
<span style="color: var(--semi-color-primary); font-weight: 600">📁 重要文件</span>
{/snippet}
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
带样式的标题
</Button>
</Upload>Replace the whole title area
fileListHeader replaces the whole title area, including the clear button. Once the snippet is provided, the default title does not come back even when it renders nothing. The snippet receives the following parameters:
fileList: Current file listonClear: Function to clear filesclearText: Default text for the clear button (based on current locale)
Code
<script lang="ts">
import { IconClose, IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const action = 'https://api.semi.design/upload';
const initialList = (): FileItem[] => [
{
uid: '1',
name: 'document.pdf',
status: 'success',
size: '130KB',
},
{
uid: '2',
name: 'report.xlsx',
status: 'success',
size: '222KB',
},
];
</script>
<Upload {action} fileList={initialList()} style="margin-bottom: 20px">
{#snippet fileListHeader({ fileList, onClear, clearText })}
<div style="display: flex; align-items: center; justify-content: space-between; width: 100%">
<span style="color: var(--semi-color-primary)">📂 共 {fileList.length} 个文件</span>
<Button size="small" type="danger" onclick={onClear}>
{#snippet icon()}<IconClose />{/snippet}
{clearText}
</Button>
</div>
{/snippet}
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
自定义清空按钮样式
</Button>
</Upload>
<Upload {action} fileList={initialList()}>
{#snippet fileListHeader({ fileList, onClear })}
<div style="display: flex; align-items: center; justify-content: space-between; width: 100%">
<span>
已选择
<strong style="color: var(--semi-color-danger)">{fileList.length}</strong>
个文件
</span>
<button style="padding: 0; border: none; background: none; font: inherit; cursor: pointer; color: var(--semi-color-link); font-size: 12px" type="button" onclick={onClear}>全部移除</button>
</div>
{/snippet}
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
完全自定义标题区域
</Button>
</Upload>Custom preview logic
When listType is list, the preview logic can be implemented through the previewFile snippet. Its content replaces the thumbnail, and the default thumbnail does not come back even when the snippet renders nothing.
For example, when you don't need thumbnail preview for image types, you can constantly render a <IconFile /> in previewFile.
If you want to enlarge and preview the image when clicked, you can use the Image component in previewFile.
Or if you want to use an additional operation area to achieve enlarged preview when clicked, you can also combine fileOperation to place some custom elements such as Icon to achieve enlarged preview when clicked.
Code
<script lang="ts">
import { IconFile, IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Image, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const url = '/assets/root-web-sites/edit-bag.jpeg';
const fileList: FileItem[] = [
{ uid: '1', name: 'dyBag.png', status: 'success', size: '130KB', url },
{ uid: '2', name: 'dyBag2.png', status: 'success', size: '130KB', url },
];
</script>
<Upload action="https://api.semi.design/upload" {fileList}>
{#snippet previewFile({ file })}
{#if file.uid === '1'}
<IconFile size="large" />
{:else}
<Image alt="" src={file.url} />
{/if}
{/snippet}
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>The following is an example of combining the fileOperation snippet and ImagePreview. In this example, clicking the first Icon on the right can enlarge the image for preview.

Code
<script lang="ts">
import { IconDelete, IconDownload, IconExpand, IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, ImagePreview, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
let visible = $state(false);
const fileList: FileItem[] = [
{
uid: '1',
name: 'dyBag.png',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/root-web-sites/edit-bag.jpeg',
},
];
</script>
<Upload action="https://api.semi.design/upload" {fileList} itemStyle="width: 300px">
{#snippet fileOperation({ file, onRemove })}
<div style="display: flex; column-gap: 8px; padding: 0 8px">
<Button aria-label="预览" size="small" theme="borderless" type="tertiary" onclick={() => (visible = true)}>
{#snippet icon()}<IconExpand />{/snippet}
</Button>
<Button aria-label="下载" size="small" theme="borderless" type="tertiary">
{#snippet icon()}<IconDownload />{/snippet}
</Button>
<Button aria-label="删除" size="small" theme="borderless" type="tertiary" onclick={() => onRemove()}>
{#snippet icon()}<IconDelete />{/snippet}
</Button>
<ImagePreview bind:visible src={file.url} />
</div>
{/snippet}
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Default file list
The uploaded files can be displayed through defaultFileList. When you need to preview the thumbnail of the default file, you can set the preview attribute of the corresponding item in defaultFileList to true


Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const fileList: FileItem[] = [
{
uid: '1',
name: 'dyBag.jpeg',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/root-web-sites/edit-bag.jpeg',
},
{
uid: '2',
name: 'dyBag2.jpeg',
status: 'uploadFail',
size: '222KB',
preview: true,
fileInstance: new File([new ArrayBuffer(2048)], 'dyBag2.jpeg', { type: 'image/png' }),
url: '/assets/root-web-sites/edit-bag.jpeg',
},
];
</script>
<Upload action="https://api.semi.design/upload" {fileList}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Controlled component
Bind the file list with bind:fileList; Upload writes it back whenever the list changes. A plain fileList value that is not bound is the initial list, which Upload then maintains itself. onChange still receives { fileList, currentFile }, where currentFile is null after files are added with the insert method.

Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type FileItem, type UploadOnChangeProps } from '@fibrae/semi-ui-svelte';
let list = $state<FileItem[]>([
{
uid: '1',
name: 'dyBag.jpeg',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/root-web-sites/edit-bag.jpeg',
},
{
uid: '2',
name: 'dy.jpeg',
status: 'uploading',
size: '222KB',
percent: 50,
preview: true,
fileInstance: new File([new ArrayBuffer(2048)], 'dy.jpeg', { type: 'image/jpeg' }),
url: '/assets/placeholder/avatar-a.svg',
},
]);
const onChange = ({ fileList, currentFile }: UploadOnChangeProps) => {
console.log('change', fileList, currentFile);
};
</script>
<Upload action="https://api.semi.design/upload" bind:fileList={list} {onChange} showRetry={false}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Photo Wall
Set listType ='picture', users can upload pictures and display thumbnails in the list
When the uploaded file list is set through defaultFileList or fileList, the url property of the objects in the array is read automatically to display the pictures
Code
<script lang="ts">
import { IconPlus } from '@fibrae/semi-icons-svelte';
import { Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const fileList: FileItem[] = [
{
uid: '1',
name: 'dy.png',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/placeholder/avatar-a.svg',
},
];
</script>
<Upload accept="image/*" action="https://api.semi.design/upload" {fileList} listType="picture" multiple>
<IconPlus aria-label="上传图片" size="extra-large" />
</Upload>Set showPicInfo, you can view the basic information of the picture
Code
<script lang="ts">
import { IconPlus } from '@fibrae/semi-icons-svelte';
import { Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const url = '/assets/placeholder/avatar-b.svg';
const fileList: FileItem[] = [
{ uid: '1', name: 'music.png', status: 'success', size: '130KB', preview: true, url },
{ uid: '2', name: 'brand.png', status: 'success', size: '130KB', preview: true, url },
];
</script>
<Upload accept="image/*" action="https://api.semi.design/upload" {fileList} listType="picture" multiple showPicInfo>
<IconPlus aria-label="上传图片" size="extra-large" />
</Upload>Photo Wall With Preview
With the Image component, through the thumbnail snippet, you can click on the image to enlarge the preview
Code
<script lang="ts">
import { IconPlus } from '@fibrae/semi-icons-svelte';
import { Image, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const action = 'https://api.semi.design/upload';
const fileList: FileItem[] = [
{
uid: '1',
name: 'music.png',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/placeholder/avatar-b.svg',
},
];
</script>
<Upload accept="image/*" {action} {fileList} listType="picture" multiple>
{#snippet thumbnail({ file })}
<Image alt={file.name} src={file.url} />
{/snippet}
<IconPlus aria-label="Upload picture" size="extra-large" />
</Upload>You can customize the preview icon through the picPreviewIcon snippet and onPreviewClick, when the replacement icon showReplace is displayed, the preview icon will no longer be displayed.
When you need to customize the preview/replacement function, you need to turn off the replacement function and use onPreviewClick to listen for clicks.
onPreviewClick listens for the click event of the single image container. Passing it also makes the file cards clickable and shows a preview button
Code
<script lang="ts">
import { IconEyeOpened, IconPlus } from '@fibrae/semi-icons-svelte';
import { Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const fileList: FileItem[] = [
{
uid: '1',
name: 'resso.png',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/placeholder/avatar-b.svg',
},
];
const handlePreview = (file: FileItem) => {
window.open(file.url, 'imagePreview', 'width=300,height=300');
};
</script>
<Upload accept="image/*" action="https://api.semi.design/upload" {fileList} listType="picture" multiple onPreviewClick={handlePreview} showPicInfo>
{#snippet picPreviewIcon()}
<IconEyeOpened style="color: var(--semi-color-white); font-size: 24px" />
{/snippet}
<IconPlus aria-label="上传图片" size="extra-large" />
</Upload>Photo Wall Width/Height
By setting picHeight, picWidth, the width and height of picture wall elements can be uniformly set. If you also render an Image component in the thumbnail snippet for click-to-enlarge preview, you need to specify both the width and height of the Image component
Code
<script lang="ts">
import { IconPlus } from '@fibrae/semi-icons-svelte';
import { Image, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const fileList: FileItem[] = [
{
uid: '1',
name: 'image-1.jpg',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/root-web-sites/abstract.jpg',
},
];
</script>
<Upload accept="image/*" action="https://api.semi.design/upload" {fileList} listType="picture" multiple picHeight={110} picWidth={200}>
{#snippet thumbnail({ file })}
<Image alt={file.name} height={110} src={file.url} width={200} />
{/snippet}
<IconPlus aria-label="上传图片" size="extra-large" style="margin: 4px" />
点击添加图片
</Upload>Set hotSpotLocation to customize the order of click hotspots, the default is at the end of the photo wall list
Code
<script lang="ts">
import { IconPlus } from '@fibrae/semi-icons-svelte';
import { Radio, RadioGroup, Upload, type FileItem, type UploadProps } from '@fibrae/semi-ui-svelte';
const action = 'https://api.semi.design/upload';
const fileList: FileItem[] = [
{
uid: '1',
name: 'resso.png',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/placeholder/avatar-b.svg',
},
];
const handlePreview = (file: FileItem) => {
window.open(file.url, 'imagePreview', 'width=300,height=300');
};
let hotSpotLocation = $state<UploadProps['hotSpotLocation']>('end');
</script>
<RadioGroup aria-label="添加按钮位置" bind:value={hotSpotLocation} type="button">
<Radio value="start">start</Radio>
<Radio value="end">end</Radio>
</RadioGroup>
<hr />
<Upload accept="image/*" {action} {fileList} {hotSpotLocation} listType="picture" multiple onPreviewClick={handlePreview} showPicInfo>
<IconPlus aria-label="上传图片" size="extra-large" />
</Upload>Disabled
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type FileItem } from '@fibrae/semi-ui-svelte';
const fileList: FileItem[] = [
{
uid: '1',
name: 'first.png',
status: 'success',
size: '130KB',
preview: true,
url: '/assets/placeholder/avatar-a.svg',
},
{
uid: '2',
name: 'second.png',
status: 'validateFail',
size: '222KB',
preview: true,
url: '/assets/placeholder/avatar-a.svg',
},
];
</script>
<Upload action="https://api.semi.design/upload" disabled {fileList}>
<Button disabled theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Manually trigger upload
uploadTrigger="custom", the upload will not be triggered automatically after the file is selected. Get the instance with bind:this and call its upload method to trigger it
Code
<script lang="ts">
import { IconPlus, IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type UploadHandle } from '@fibrae/semi-ui-svelte';
let upload = $state<UploadHandle>();
const action = 'https://api.semi.design/upload';
</script>
<div>
<Upload accept="image/gif, image/png, image/jpeg, image/bmp, image/webp" {action} bind:this={upload} onError={(...v) => console.log(...v)} onSuccess={(...v) => console.log(...v)} uploadTrigger="custom">
<Button style="margin-inline-end: 8px" theme="light">
{#snippet icon()}<IconPlus />{/snippet}
选择文件
</Button>
</Upload>
<Button theme="light" onclick={() => upload?.upload()}>
{#snippet icon()}<IconUpload />{/snippet}
开始上传
</Button>
</div>Drag and drop upload
draggable='true', you can use the drag and drop function
Code
<script lang="ts">
import { Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload action="https://api.semi.design/upload" draggable>
{#snippet dragMainText()}点击上传文件或拖拽文件到这里{/snippet}
{#snippet dragSubText()}支持任意类型文件{/snippet}
</Upload>You can quickly set the content of the drag area through the dragIcon, dragMainText, dragSubText snippets. dragIcon and dragMainText fall back to the default icon and text when they render nothing
Code
<script lang="ts">
import { IconBolt } from '@fibrae/semi-icons-svelte';
import { Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload accept="application/pdf,.jpeg" action="https://api.semi.design/upload" draggable style="margin-top: 10px">
{#snippet dragIcon()}
<IconBolt />
{/snippet}
{#snippet dragMainText()}点击上传文件或拖拽文件到这里{/snippet}
{#snippet dragSubText()}仅支持jpeg、pdf{/snippet}
</Upload>You can also pass content through children to completely customize the display of the drag area
Code
<script lang="ts">
import { IconBolt } from '@fibrae/semi-icons-svelte';
import { Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload accept="application/pdf,.jpeg" action="https://api.semi.design/upload" draggable style="margin-top: 10px">
{#snippet dragIcon()}
<IconBolt />
{/snippet}
<div class="components-upload-demo-drag-area">
<img alt="demo img" height="96" src="/assets/placeholder/avatar-a.svg" style="border-radius: 4px" />
<div style="font-size: 14px; margin-top: 8px; flex-basis: 100%; text-align: center; color: var(--semi-color-tertiary)">Wow, you can really dance.</div>
</div>
</Upload>The scss style is as follows
.components-upload-demo-drag-area {
border-radius: var(--semi-border-radius-small);
border: 2px dashed var(--semi-color-border);
width: 100%;
padding: 12px;
background-color: var(--semi-color-tertiary-light-default);
display: flex;
cursor: pointer;
flex-wrap: wrap;
justify-content: center;
&:hover {
background-color: var(--semi-color-primary-light-default);
border-color: var(--semi-color-primary);
}
}
Paste upload
With addOnPasting, files pasted anywhere on the page (the paste event) are added to the file list, with no clipboard permission prompt. onPastingError is called when a pasted file cannot be read.
Code
<script lang="ts">
import { Toast, Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload action="https://api.semi.design/upload" addOnPasting draggable onPastingError={() => Toast.error('读取剪贴板中的文件失败')}>
{#snippet dragMainText()}复制截图或文件后,在页面上按 Ctrl/Cmd + V{/snippet}
{#snippet dragSubText()}也可以点击或拖拽上传{/snippet}
</Upload>Custom check before upload
The file status can be updated through the beforeUpload hook, which is to verify the file after selecting the file before uploading online, ({ file: FileItem, fileList: Array<FileItem> }) => beforeUploadResult | Promise | boolean During synchronization verification, a boolean (true means the verification passed, false means the verification failed, and the verification failure will prevent the file from uploading online) or an Object object. The specific structure is as follows
// beforeUploadResult:
{
fileInstance?: File,
status?:'success' |'uploadFail' |'validateFail' |'validating' |'uploading' |'wait',
validateMessage?: string, // file validation information; use the fileValidateMessage snippet for a node
shouldUpload: boolean, // Whether to upload. The default is true, if it is false, the fileItem will only be displayed in the list, and the upload operation will not be triggered
autoRemove: boolean, // Whether to remove the file from the fileList, the default is false
}
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type BeforeUploadObjectResult, type BeforeUploadProps } from '@fibrae/semi-ui-svelte';
let count = 0;
const transformFile = (fileInstance: File) => {
if (count === 0) {
return new File([fileInstance], 'newFileName', { type: 'image/png' });
}
return fileInstance;
};
const beforeUpload = ({ file }: BeforeUploadProps) => {
let result: BeforeUploadObjectResult;
if (count > 0) {
result = {
autoRemove: false,
fileInstance: file.fileInstance,
shouldUpload: true,
};
} else {
result = {
autoRemove: false,
fileInstance: file.fileInstance,
status: 'validateFail',
shouldUpload: false,
};
}
count += 1;
return result;
};
</script>
<Upload action="https://api.semi.design/upload" {beforeUpload} {transformFile}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传(上传前同步校验)
</Button>
</Upload>In the case of asynchronous verification, a Promise must be returned. Promise resolve means that the verification is passed, and reject means that the verification fails and the upload will not be triggered. Object can be passed in when resolve/reject (the structure is the same as beforeUploadResult)
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type BeforeUploadObjectResult, type BeforeUploadProps } from '@fibrae/semi-ui-svelte';
let count = 0;
const beforeUpload = ({ file }: BeforeUploadProps) => {
return new Promise<BeforeUploadObjectResult>((resolve, reject) => {
if (count > 1) {
count += 1;
resolve({ autoRemove: false, shouldUpload: true });
} else {
const result: BeforeUploadObjectResult = {
autoRemove: false,
fileInstance: file.fileInstance,
status: 'validateFail',
shouldUpload: false,
validateMessage: `第${count + 1}个注定失败`,
};
count += 1;
reject(result);
}
});
};
</script>
<Upload action="https://api.semi.design/upload" {beforeUpload}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传(上传前异步校验)
</Button>
</Upload>Update file information after upload
The file status, verification information, and file name can be updated through the afterUpload hook. ({ response: any, file: FileItem, fileList: Array<FileItem> }) => afterUploadResult afterUpload is triggered when the upload is completed (xhr.onload) and no error occurs, it needs to return an Object object (asynchronous return is not supported), the specific structure is as follows
// afterUploadResult:
{
status?:'success' |'uploadFail' |'validateFail' |'validating' |'uploading' |'wait',
validateMessage?: string, // file validation information; use the fileValidateMessage snippet for a node
autoRemove?: boolean, // Whether to remove the file from the fileList, the default is false
name?: string;
// The URL for previewing image file, usually the storage address returned by the Server after receiving response
url?: string;
}
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type AfterUploadProps, type AfterUploadResult } from '@fibrae/semi-ui-svelte';
const afterUpload = ({ response }: AfterUploadProps): AfterUploadResult => {
if (response.status_code === 200) {
return {
autoRemove: false,
status: 'uploadFail',
validateMessage: '内容不合法',
name: 'RenameByServer.jpg',
url: '/assets/root-web-sites/edit-bag.jpeg',
};
}
return {};
};
</script>
<Upload action="https://api.semi.design/upload" {afterUpload}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Custom request
When customRequest is passed in, it is equivalent to using the custom request method to replace the upload built-in xhr request, and the user needs to take over the upload behavior by himself. The file object of the current operation can be obtained in the input parameters, and the user implements the upload process by himself, and calls onProgress, onError, and onSuccess in the customRequest input parameters when appropriate to update the internal state of the Upload component customRequest contains the following input parameters
{
// current file name
fileName: string,
// props.data set by the user
data: object,
// FileItem, refer to the following document for the specific structure
file: FileItem,
// original File Object which extends Blob, the file object actually obtained by the browser (https://developer.mozilla.org/zh-CN/docs/Web/API/File)
fileInstance: File,
// Function that should be called during upload, event needs to include total and loaded attributes
onProgress: (event: {total: number, loaded: number }) => any,
// Function to be called when upload error
onError: (userXhr: { status?: number }, e?: Event) => any,
// The function that should be called after the upload is successful, response is the request result after the upload is successful
onSuccess: (response: any, e?: Event) => any,
// props.withCredentials set by the user
withCredentials: boolean,
// props.action set by the user
action: string,
}
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type UploadCustomRequestArgs } from '@fibrae/semi-ui-svelte';
const mockRequest = ({ onProgress, onSuccess }: UploadCustomRequestArgs) => {
let count = 0;
const interval = setInterval(() => {
if (count === 100) {
clearInterval(interval);
onSuccess({});
return;
}
onProgress({ total: 100, loaded: count });
count += 20;
}, 500);
};
</script>
<Upload action="https://api.semi.design/upload" customRequest={mockRequest}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传
</Button>
</Upload>Image Cropping
Enable image cropping functionality through the crop property. Supports cropping when clicking to select, dragging, pasting, and replacing files.
Basic Usage
Set crop to enable default cropping configuration (crop={true} or the boolean shorthand crop).
accept and limit are applied before cropping, so images that are rejected or exceed the limit are never cropped. Browsers encode only PNG, JPEG and WebP; the cropped result of any other format (GIF, BMP, SVG) is a PNG, and the file's type and extension become image/png and .png.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
</script>
<Upload action="https://api.semi.design/upload" crop onSuccess={(response, file) => console.log('上传成功:', response, file)}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传(启用裁切)
</Button>
</Upload>Custom Cropping Configuration
Configure cropping parameters through object form, including aspect ratio, shape, quality, etc.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type UploadCropProps } from '@fibrae/semi-ui-svelte';
const crop: UploadCropProps = {
aspectRatio: 16 / 9,
shape: 'rect',
quality: 0.8,
modalTitle: '裁切图片',
modalOkText: '确认裁切',
modalCancelText: '取消',
};
</script>
<Upload action="https://api.semi.design/upload" {crop} onSuccess={(response, file) => console.log('上传成功:', response, file)}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传(16:9 裁切)
</Button>
</Upload>Round Cropping
Suitable for avatar upload scenarios, set shape: 'round' to enable round cropping.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
const crop = {
aspectRatio: 1,
shape: 'round',
quality: 0.9,
modalTitle: '裁切头像',
} as const;
</script>
<Upload action="https://api.semi.design/upload" {crop} onSuccess={(response, file) => console.log('上传成功:', response, file)}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传(圆形裁切)
</Button>
</Upload>Confirm Before Cropping
Use the beforeCrop callback to confirm or perform other processing before cropping. Return false to skip cropping and upload directly.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload, type UploadProps } from '@fibrae/semi-ui-svelte';
const crop = { aspectRatio: 1, shape: 'round' } as const;
const beforeCrop: UploadProps['beforeCrop'] = (file, fileList) => {
console.log('beforeCrop:', file, fileList);
// true continues cropping; false skips it and uploads directly
return window.confirm('是否裁切图片?');
};
</script>
<Upload action="https://api.semi.design/upload" {beforeCrop} {crop} onCropError={(error) => console.error('裁切失败:', error)} onSuccess={(response, file) => console.log('上传成功:', response, file)}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
点击上传(裁切前确认)
</Button>
</Upload>Drag and Drop Upload with Cropping
Cropping is also triggered when uploading via drag and drop.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
const crop = {
aspectRatio: 1,
shape: 'rect',
} as const;
</script>
<Upload action="https://api.semi.design/upload" {crop} draggable onDrop={(_e, files) => console.log('拖拽文件:', files)} onSuccess={(response, file) => console.log('上传成功:', response, file)}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
拖拽上传(启用裁切)
</Button>
</Upload>Custom Cropping Modal Style
Customize the style and properties of the cropping modal through cropModalProps. The width of the modal defaults to 600, and the value passed in wins.
cropModalProps is typed as UploadCropModalProps, which leaves out visible, title, okText, cancelText, onOk and onCancel: set the title and button texts with modalTitle, modalOkText and modalCancelText of crop, and the rest belongs to Upload.
Code
<script lang="ts">
import { IconUpload } from '@fibrae/semi-icons-svelte';
import { Button, Upload } from '@fibrae/semi-ui-svelte';
const crop = {
aspectRatio: 1,
shape: 'rect',
} as const;
const cropModalProps = {
width: 800,
style: 'height: 600px',
bodyStyle: 'height: 500px; background-color: #f5f5f5',
};
</script>
<Upload action="https://api.semi.design/upload" {crop} {cropModalProps} onSuccess={(response, file) => console.log('上传成功:', response, file)}>
<Button theme="light">
{#snippet icon()}<IconUpload />{/snippet}
自定义弹窗样式
</Button>
</Upload>API Reference
Upload
Props
| Property | Description | Type | Default |
|---|---|---|---|
| accept | Accepted file types, written like the accept attribute of input: file extensions such as .jpg or MIME types, separated by commas. | string | - |
| action | Upload URL. Required. | string | - |
| addOnPasting | Whether files in the clipboard are added to the file list on paste, without extra permission. | boolean | false |
| afterUpload | Hook after an upload completes without error. The returned object updates the file status, validate message, name and preview URL. Async results are not supported. | Type(object: AfterUploadProps) => AfterUploadResult | - |
| beforeClear | Called before the list is cleared. Returning false, or a Promise that resolves to false or rejects, blocks the clear. | Type(fileList: FileItem[]) => boolean | Promise<boolean> | - |
| beforeCrop | Called before the crop modal opens, once with the first selected image; the result decides cropping for the whole batch. Return false to upload without cropping. May return a Promise. | Type(file: File, fileList: File[]) => boolean | Promise<boolean> | - |
| beforeRemove | Called before a file is removed. Returning false, or a Promise that resolves to false or rejects, blocks the removal. | Type(file: FileItem, fileList: FileItem[]) => boolean | Promise<boolean> | - |
| beforeUpload | Hook before a file is uploaded. The returned object updates the file status and decides whether to upload. A boolean means pass or fail; for a Promise, resolve passes and reject fails. | Type(object: BeforeUploadProps) => BeforeUploadObjectResult | Promise<BeforeUploadObjectResult> | boolean | - |
| capture | How media is captured: user or environment. true renders the attribute with an empty value, false omits it. | boolean | 'user' | 'environment' | - |
| children | Trigger content. In draggable mode it replaces the whole default drag area content. | Snippet | - |
| crop | Enables image cropping. true uses the defaults, an object configures the cropper. Selecting, dragging, pasting and replacing all crop. | boolean | UploadCropProps | false |
| cropModalProps | Props of the crop Modal. visible, title, okText, cancelText, onOk, onCancel and children belong to Upload; style and bodyStyle are style strings. | UploadCropModalProps | - |
| customRequest | Replaces the built-in XMLHttpRequest. It must call the onProgress, onError and onSuccess it receives to update the state. | Type(object: UploadCustomRequestArgs) => void | - |
| data | Extra parameters sent with the upload, or a function that returns them for a file. | TypeRecord<string, any> | ((file: File) => Record<string, unknown>) | - |
| directory | Whether to upload a folder. | boolean | false |
| disabled | Whether Upload is disabled. A disabled Upload no longer shows the remove, retry, replace and clear actions. | boolean | false |
| draggable | Whether dragging files to upload is supported. | boolean | false |
| dragIcon | Icon of the drag area. Falls back to the default icon when empty. | Snippet | - |
| dragMainText | Main text of the drag area. Falls back to the locale text when empty. | Snippet | - |
| dragSubText | Help text of the drag area. | Snippet | - |
| ellipsisTooltip | Custom popup content for a truncated file name, with content and trigger; trigger is the file name element to place in the popup. | TypeSnippet<[TypographyEllipsisTooltipProps]> | - |
| fileItem | Replaces each file card, with UploadFileItemSlotProps. Render <UploadFileCard {...props} /> for the default card. A file it renders nothing for is not shown. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| fileList | The file list, two-way bindable with bind:fileList. A plain value is the initial list, which Upload then maintains itself. The uid of every item is required and must be unique. | FileItem[] | - |
| fileListHeader | Replaces the whole title area, clear button included, with fileList, onClear and clearText. | TypeSnippet<[UploadFileListHeaderSlotProps]> | - |
| fileListTitle | Replaces only the title text of the file list; the clear button stays. | Snippet | - |
| fileName | Same as name. Mainly used in Form.Upload to avoid clashing with the name of Field. | string | - |
| fileOperation | Custom operation area of a list item. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| fileValidateMessage | Custom validate message of a file card, which receives validateMessage. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| headers | Headers sent with the upload, or a function that returns them for a file. | TypeRecord<string, any> | ((file: File) => Record<string, string>) | - |
| hotSpotLocation | Position of the picture wall add button: start or end. | 'start' | 'end' | "end" |
| itemStyle | Style string of the file cards. | string | - |
| limit | Maximum number of files. With 1, the newest file always replaces the current one and onExceed is not called. | number | - |
| listType | How the file list is displayed: list, picture or none. none renders no file list, only the trigger area. | UploadListType | "list" |
| maxSize | Maximum file size in KB. | number | - |
| minSize | Minimum file size in KB. | number | - |
| multiple | Whether several files can be selected at once. | boolean | false |
| name | Field name used for the file when uploading. | string | - |
| onAcceptInvalid | Called when received files do not match accept, with those files. | Type(files: File[]) => void | - |
| onChange | Called when a file status changes, including uploading, success and failure. currentFile is null after insert and absent after a clear. This is the callback of Upload, not the native change of the hidden input. | Type(object: UploadOnChangeProps) => void | - |
| onClear | Called after the list is cleared. | Type() => void | - |
| onCropError | Called when cropping an image fails. | Type(error: Error) => void | - |
| onDrop | Called when a dragged element is released on the drag area, with the native drop event, the dropped files and the current file list. | Type(e: DragEvent, files: File[], fileList: FileItem[]) => void | - |
| onError | Called when an upload fails. With customRequest, xhr is the object passed to its onError. | Type(e: UploadCustomError, file: CustomFile, fileList: FileItem[], xhr: XMLHttpRequest | { status?: number }) => void | - |
| onExceed | Called when the total number of files exceeds limit, with the originally selected files before truncation. | Type(fileList: File[]) => void | - |
| onFileChange | Called after files are selected. | Type(files: File[]) => void | - |
| onOpenFileDialog | Called when the system file dialog opens. | Type() => void | - |
| onPastingError | Called when addOnPasting is true and a clipboard file cannot be read. | Type(error: Error) => void | - |
| onPreviewClick | While present the file cards are clickable and show a preview button; its presence changes the rendering. | Type(fileItem: FileItem) => void | - |
| onProgress | Called while uploading, with the percentage, the file and the current file list. | Type(percent: number, file: CustomFile, fileList: FileItem[]) => void | - |
| onRemove | Called after a file is removed. currentFile is undefined for an item without a File object, such as one from the initial list. | Type(currentFile: CustomFile | undefined, fileList: FileItem[], currentFileItem: FileItem) => void | - |
| onRetry | Called when retry is clicked. | Type(fileItem: FileItem) => void | - |
| onSizeError | Called when a file size violates maxSize or minSize. | Type(file: CustomFile, fileList: FileItem[]) => void | - |
| onSuccess | Called after a successful upload, with the server response, the file and the current file list. | Type(responseBody: any, file: CustomFile, fileList: FileItem[]) => void | - |
| picClose | Custom close button of the picture wall, with class and onRemove. Only applies in picture mode. | TypeSnippet<[UploadPicCloseSlotProps]> | - |
| picHeight | Display height of the pictures in picture mode. | string | number | - |
| picInfo | Custom picture wall information. Only applies in picture mode with showPicInfo set to true. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| picPreviewIcon | Custom preview icon shown on hover in the picture wall. Only applies in picture mode. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| picWidth | Display width of the pictures in picture mode. | string | number | - |
| previewFile | Custom preview that replaces the thumbnail. Only applies in list mode. It does not fall back to the default thumbnail when empty. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| prompt | Prompt text. Unlike content in children, clicking it does not trigger an upload. | Snippet | - |
| promptPosition | Position of the prompt: left, right or bottom. In list mode it is relative to the trigger, in picture mode to the picture list. | PromptPositionType | "right" |
| showClear | In list mode, whether to show the clear button when limit is not 1 and there is at least one file. | boolean | true |
| showPicInfo | Whether to show picture information. Only applies in picture mode. | boolean | false |
| showReplace | Whether the file card shows a replace button after a successful upload. | boolean | false |
| showRetry | Whether the file card shows a retry button when the upload fails. | boolean | true |
| showTooltip | Whether a truncated file name shows a tooltip, or the tooltip type (tooltip or popover) and the props passed to it. Use the ellipsisTooltip snippet for custom popup content. | boolean | ShowTooltip | true |
| showUploadList | Whether to show the file list. | boolean | true |
| thumbnail | Custom picture wall thumbnail. Only applies in picture mode. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| transformFile | Called after a file is selected and before it is uploaded; returns the File to upload. | Type(file: File) => File | - |
| uploadTrigger | When uploading starts: auto uploads on selection, custom waits for the upload method. | 'auto' | 'custom' | "auto" |
| validateMessage | Validate message of the whole Upload. | Snippet | - |
| validateStatus | Validation status, which styles the root element: default, error, warning or success. | ValidateStatus | - |
| withCredentials | Whether the upload request carries cookies. | boolean | false |
Methods
| Method | Description | Type |
|---|---|---|
| insert | Adds files at index, or at the end without one. | Type(files: CustomFile[], index?: number) => void |
| openFileDialog | Opens the file dialog. | Type() => void |
| upload | Uploads the waiting files. Use it with uploadTrigger set to custom. | Type() => void |
Undeclared attributes such as class, style and aria-* land on the root element, which gets role="group" automatically when it has aria-label or aria-labelledby.
Upload.FileCard
Upload.FileCard (also importable on its own as UploadFileCard) is the default file card, used to keep the default look inside snippets such as fileItem: <Upload.FileCard {...props} />. class, style, data-* and aria-* land on its root element.
Props
| Property | Description | Type | Default |
|---|---|---|---|
| disabled | Whether the card is disabled. A disabled card shows no remove, retry or replace button. | boolean | - |
| ellipsisTooltip | Custom popup content for a truncated file name, with content and trigger. | TypeSnippet<[TypographyEllipsisTooltipProps]> | - |
| file | The file to show. Required. | FileItem | - |
| fileOperation | Custom operation area of a list item. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| fileValidateMessage | Custom validate message, which receives validateMessage. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| index | Position of the file in the list. | number | - |
| listType | Display type of the card: list, picture or none. none renders no card. | UploadListType | "list" |
| onPreviewClick | While present the card is clickable and shows a preview button; its presence changes the rendering. | Type() => void | - |
| onRemove | Called when remove is clicked. | Type() => void | - |
| onReplace | Called when replace is clicked. | Type() => void | - |
| onRetry | Called when retry is clicked. | Type() => void | - |
| picClose | Custom close button of the picture wall, with class and onRemove. Only applies in picture mode. | TypeSnippet<[UploadPicCloseSlotProps]> | - |
| picHeight | Height of the picture in picture mode. | string | number | - |
| picInfo | Custom picture wall information. Only applies in picture mode with showPicInfo set to true. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| picPreviewIcon | Custom preview icon shown on hover in the picture wall. Only applies in picture mode. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| picWidth | Width of the picture in picture mode. | string | number | - |
| previewFile | Custom preview that replaces the thumbnail. Only applies in list mode. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| showPicInfo | Whether to show picture information. Only applies in picture mode. | boolean | - |
| showReplace | Whether to show a replace button after success. The showReplace of the file wins. | boolean | - |
| showRetry | Whether to show a retry button on failure. The showRetry of the file wins. | boolean | - |
| showTooltip | Whether a truncated file name shows a tooltip, or the tooltip type and the props passed to it. | boolean | ShowTooltip | true |
| thumbnail | Custom picture wall thumbnail. Only applies in picture mode. | TypeSnippet<[UploadFileItemSlotProps]> | - |
| validateMessage | Validate message. Wins over the validateMessage of the file. | string | - |
Interfaces
FileItem Interface
interface FileItem {
event?: Event; // xhr event
fileInstance?: File; // original File Object which extends Blob, the file object actually obtained by the browser (https://developer.mozilla.org/zh-CN/docs/Web/API/File)
name: string;
percent?: number; // upload progress percentage
preview?: boolean; // Whether to preview according to url
response?: any; // xhr's response, response body when the request is successful, and corresponding error when the request fails
shouldUpload?: boolean; // Should you continue to upload
showReplace?: boolean; // Separately control whether the file displays the replace button
showRetry?: boolean; // Separately control whether the file displays the retry button
size: string; // file size, unit kb
status: 'success' | 'uploadFail' | 'validateFail' | 'validating' | 'uploading' | 'wait';
uid: string; // The unique identifier of the file. If the current file is selected and added by upload, the uid will be automatically generated. If it is the initial list, you need to ensure that it will not be repeated
url?: string;
validateMessage?: string; // a string only; use the fileValidateMessage snippet for a node
}
FileItem has only the fields above; writing an undeclared field is a type error.
UploadFileItemSlotProps Interface
The parameter that the fileItem, thumbnail, picInfo, picPreviewIcon, fileOperation, previewFile and fileValidateMessage snippets receive. The file data sits in the file field, next to the file card's props. <Upload.FileCard {...props} /> renders the default card.
interface UploadFileItemSlotProps {
file: FileItem;
index?: number; // position of the file in the list
listType: 'picture' | 'list' | 'none';
disabled?: boolean;
showRetry?: boolean;
showReplace?: boolean;
showPicInfo?: boolean;
showTooltip?: boolean | ShowTooltip;
picWidth?: string | number;
picHeight?: string | number;
validateMessage?: string;
style?: string; // from itemStyle
onRemove: () => void; // removes this file
onRetry: () => void; // uploads this file again
onReplace: () => void; // replaces this file
onPreviewClick?: () => void; // present only when Upload has an onPreviewClick
}
UploadPicCloseSlotProps Interface
The parameter that picClose receives:
interface UploadPicCloseSlotProps {
class: string;
onRemove: (e: MouseEvent) => void;
}
UploadFileListHeaderSlotProps Interface
The parameter that fileListHeader receives:
interface UploadFileListHeaderSlotProps {
fileList: FileItem[]; // Current file list
onClear: () => void; // Function to clear files
clearText: string; // Default text for the clear button (based on current locale)
}
CropProps Interface
Configuration object accepted by the crop prop:
In Svelte the type is exported as UploadCropProps.
interface CropProps {
aspectRatio?: number; // Crop box aspect ratio, e.g. 16/9, 1, 4/3
shape?: 'rect' | 'round' | 'roundRect'; // Crop box shape, default 'rect'
minZoom?: number; // Minimum zoom ratio
maxZoom?: number; // Maximum zoom ratio
zoomStep?: number; // Zoom step size
quality?: number; // Output image quality, range 0 - 1, default 0.92
fill?: string; // Fill color of the area outside the cropped region, default transparent 'rgba(0, 0, 0, 0)'
modalTitle?: string; // Title text of the crop modal
modalOkText?: string; // Confirm button text of the crop modal
modalCancelText?: string; // Cancel button text of the crop modal
}
Methods
Upload exposes insert, upload and openFileDialog as export functions. Get the instance with bind:this, typed as UploadHandle; see the Methods table of Upload above.
Accessibility
The Upload component is an interactive control that can trigger file selection when clicking or dragging. After the file is selected, the status will be displayed in the file list.
ARIA
- The trigger area is a
role="button"that Enter and Space activate. When the trigger content holds its own control, such as a Button, the area takes no role and that control is the button; its click opens the file dialog. A disabled control (nativedisabledoraria-disabled="true") still counts as your own control: the area does not become a button, and Enter and Space do not open the file dialog - When Upload is disabled, pass
disabledto that control as well. Whenlimitis reached, disable only that control and not Upload, so users can still remove uploaded files - When the root element has
aria-labeloraria-labelledby, it getsrole="group"automatically; aroleyou pass yourself wins - Add
role="list"to the file list and describe it witharia-label; in the picture wall the add button sits beside the list - In list mode the replace button is the trigger of its Tooltip, so Tab stops on it once
Content Guidelines
- Upload button
- For the copywriting specification of the form button, refer to The content Guidelines of the Button component
- Help text
- The help text is written in sentences, the first letter is capitalized, and periods may not be required
- Error message
- Clearly tell the user why the file cannot be uploaded, and tell the user how to upload it successfully
- Help texts are written using sentences, capitalized
- Concise language that users can read at a glance, such as
File size must be less than 20MB,File type must be .gif, .jpg, .png or .svg
Design Tokens
| Sass variable | Value | Usage |
|---|---|---|
| $color-upload-text | var(--semi-color-text-0) | 上传文件卡片等默认文本颜色 |
| $color-upload_assist-text | var(--semi-color-text-2) | 上传文件列表标题及文件大小文本颜色 |
| $color-upload-border | var(--semi-color-border) | 图片墙添加按钮及拖拽区域描边颜色 |
| $color-upload_card-bg-hover | var(--semi-color-fill-1) | 上传文件卡片背景色 - 悬浮 |
| $color-upload_card-bg | var(--semi-color-fill-0) | 上传文件卡片背景色 - 默认 |
| $color-upload_card_fail-bg-hover | var(--semi-color-danger-light-hover) | 上传失败文件卡片背景色 - 悬浮 |
| $color-upload_card_fail-bg | var(--semi-color-danger-light-default) | 上传失败文件卡片背景色 - 默认 |
| $color-upload_clear-text | var(--semi-color-primary) | 上传清空按钮文本颜色 |
| $color-upload_drag_area-bg-hover | var(--semi-color-primary-light-default) | 上传可拖拽区域背景颜色 - 悬浮 |
| $color-upload_drag_area-border-hover | var(--semi-color-primary) | 上传可拖拽区域描边颜色 - 悬浮 |
| $color-upload_drag_area_disabled-text | var(--semi-color-disabled-text) | 上传可拖拽区域禁用文本颜色 |
| $color-upload_drag_area-bg | var(--semi-color-tertiary-light-default) | 上传可拖拽区域背景颜色 - 默认 |
| $color-upload_drag_area_icon | var(--semi-color-primary) | 上传可拖拽区域图标颜色 |
| $color-upload_drag_area_tips-text | var(--semi-color-primary) | 上传可拖拽区域提示文本颜色 |
| $color-upload_drag_area_main-text-default | var(--semi-color-text-0) | 上传可拖拽区主要提示文本颜色 - 默认 |
| $color-upload_drag_area_main-text-hover | var(--semi-color-text-0) | 上传可拖拽区主要提示文本颜色 - 悬浮 |
| $color-upload_drag_area_main-text-active | var(--semi-color-text-0) | 上传可拖拽区主要提示文本颜色 - 按下 |
| $color-upload_drag_area_sub-text-default | var(--semi-color-text-0) | 上传可拖拽区次要提示文本颜色 - 默认 |
| $color-upload_drag_area_sub-text-hover | var(--semi-color-text-0) | 上传可拖拽区次要提示文本颜色 - 悬浮 |
| $color-upload_drag_area_sub-text-active | var(--semi-color-text-0) | 上传可拖拽区次要提示文本颜色 - 按下 |
| $color-upload_file_card_fail_info-text | var(--semi-color-danger) | 上传文件卡片失败提示信息文本颜色 |
| $color-upload_file_card_preview_placeholder-bg | var(--semi-grey-3) | 文件卡片默认预览背景颜色 |
| $color-upload_file_card_preview_placeholder-text | var(--semi-white) | 文件卡片默认预览图颜色 |
| $color-upload_file_card_retry-bg | var(--semi-color-white) | 图片墙上传卡片重新上传按钮背景颜色 |
| $color-upload_file_card_retry-text | var(--semi-color-primary) | 图片墙上传卡片重新上传按钮文本颜色 |
| $color-upload-icon | var(--semi-color-tertiary) | 图片墙上传图标加号颜色 |
| $color-upload_pic_add-bg-active | var(--semi-color-fill-2) | 图片墙上传背景色 - 按下 |
| $color-upload_pic_add-bg-hover | var(--semi-color-fill-1) | 图片墙上传背景色 - 悬浮 |
| $color-upload_pic_add-bg | var(--semi-color-fill-0) | 图片墙上传背景色 - 默认 |
| $color-upload_picture_file_card_loading_error-icon | var(--semi-color-danger) | 图片墙上传卡片加载及失败状态图标颜色 |
| $color-upload_picture_file_card_error-border | var(--semi-color-danger) | 图片墙上传卡片失败状态描边颜色 |
| $color-upload_picture_file_card_pic_info-text | var(--semi-color-white) | 图片墙图片信息(序号)文字颜色 |
| $color-upload_picture_file_card_close-icon | var(--semi-color-white) | 图片墙关闭图标颜色 |
| $color-upload_picture_file_card_hover-bg | var(--semi-color-overlay-bg) | 图片墙预览悬浮背景色 |
| $color-upload_preview-icon | var(--semi-color-text-2) | 上传文件卡片文本颜色 |
| $color-upload_retry-text | var(--semi-color-primary) | 上传文件卡片重新上传按钮文本颜色 |
| $color-upload_replace-text | var(--semi-color-white) | 图片墙上传卡片替换按钮文本颜色 |
| $height-upload_file_card | 52px | 上传文件卡片高度 |
| $width-upload_file_card | 250px | 上传文件卡片宽度 |
| $height-upload_file_pic_card | 96px | 图片墙上传卡片高度 |
| $width-upload_file_pic_card | 96px | 图片墙上传卡片宽度 |
| $width-upload_file_card_preview | 36px | 文件卡片预览图标宽度 |
| $height-upload_file_card_preview | 36px | 文件卡片预览图标高度 |
| $width-upload_file_card_preview_img | 36px | 文件卡片预览图片宽度 |
| $width-upload_file_card-icon | 11px | 文件卡片图标宽度 |
| $width-upload_picture_add-border | 2px | 图片墙添加按钮描边宽度 |
| $width-upload_picture_file_card_img | 96px | 图片墙上传卡片宽度 |
| $width-upload_picture_file_card_close | 16px | 图片墙上传卡片删除按钮图标宽度 |
| $width-upload_file_card_retry | 24px | 重新上传按钮宽度 |
| $width-upload_file_card_retry-icon | 13px | 重新上传按钮图标宽度 |
| $width-upload_picture_file_card_loading-icon | 14px | 上传加载 spin 宽度 |
| $width-upload_drag_area-border | 2px | 可拖拽上传描边宽度 |
| $spacing-upload_title_choosen-marginRight | $spacing-tight | 已选择文件标题右侧外边距 |
| $spacing-upload_title-marginBottom | $spacing-extra-tight | 文件列表标题底部外边距 |
| $spacing-upload_file_card_preview-margin | $spacing-tight | 上传文件卡片预览外边距 |
| $spacing-upload_file_card_info_size-marginLeft | $spacing-tight | 上传文件卡片文件大小文本左侧外边距 |
| $spacing-upload_file_card_info_retry-marginLeft | $spacing-tight | 上传文件卡片重新上传按钮左侧外边距 |
| $spacing-upload_file_card_info_progress-marginTop | 4px | 上传文件卡片进度顶部外边距 |
| $spacing-upload_file_card_close-marginLeft | $spacing-tight | 上传文件卡片删除按钮左侧外边距 |
| $spacing-upload_file_card_close-marginRight | $spacing-tight | 上传文件卡片删除按钮右侧外边距 |
| $spacing-upload_file_card_icon-marginRight | $spacing-super-tight | 上传文件卡片图标右侧外边距 |
| $spacing-upload_picture_file_card-gap | $spacing-tight | 图片墙卡片之间边距 |
| $spacing-upload_picture_file_card-marginBottom | $spacing-tight | 图片墙上传卡片底部外边距 |
| $spacing-upload_picture_file_card_close-top | 8px | 图片墙上传卡片删除按钮顶部位置 |
| $spacing-upload_picture_file_card_close-right | 8px | 图片墙上传卡片删除右侧位置 |
| $spacing-upload_picture_file_card_loading_error-bottom | 6px | 图片墙上传卡片加载中图标底部位置 |
| $spacing-upload_picture_file_card_loading_error-right | 6px | 图片墙上传卡片报错图标底部位置 |
| $spacing-upload_picture_file_card_icon_error-top | -1px | 图片墙上传卡片加载中图标顶部位置 |
| $spacing-upload_drag_area-padding | $spacing-base-tight | 可拖拽上传拖拽区域内边距 |
| $spacing-upload_drag_area_main_text-marginBottom | $spacing-extra-tight | 可拖拽上传拖拽标题底部外边距 |
| $radius-upload_file_card | var(--semi-border-radius-medium) | 上传文件卡片圆角 |
| $radius-upload_file_card_preview | var(--semi-border-radius-small) | 上传文件卡片预览图圆角 |
| $radius-upload_picture_add | var(--semi-border-radius-small) | 图片墙上传文件添加按钮圆角 |
| $radius-upload_picture_file_card_img | var(--semi-border-radius-small) | 图片墙上传卡片圆角 |
| $radius-upload_picture_file_card_close | var(--semi-border-radius-circle) | 图片墙上传卡片删除按钮圆角 |
| $radius-upload_file_card_retry | var(--semi-border-radius-circle) | 上传文件卡片重新上传圆角 |
| $radius-upload_drag_area | var(--semi-border-radius-small) | 可拖拽上传拖拽区域圆角 |
| $font-upload_file_card_info_name-fontWeight | $font-weight-bold | 上传文件卡片文件名字重 |
| $font-upload_file_card_info_size-fontWeight | $font-weight-regular | 上传文件卡片文件尺寸字重 |
| $font-upload_drag_area_tips-fontWeight | 600 | 可拖拽上传提示文本字重 |
| $font-upload_picture_file_card_pic_info-fontSize | 12px | 图片墙图片信息字体大小 |
| $font-upload_picture_file_card_pic_info-fontWeight | 600 | 图片墙图片信息文本字重 |
FAQ
- When will the retry button appear?
- When
showRetryis true and the upload of the current file fails due to a network error, the retry button will be displayed. Other statuses such as verification failed, upload successful, etc. will not display the retry button.
- When
- When will the replace button appear?
- When
showReplaceis true and the current file status is uploaded, the replace button will be displayed.
- When
- Where did Semi save the pictures?
- Semi is not responsible for the preservation of the image, you need to customize the action when you use the Upload component. You can choose to set action as your own server address or image service address.
- Form.Upload props.name does not work?
- Form.Field has props.name and so does Upload, so the two clash. With Form.Upload, use props.fileName instead to avoid the clash
- Didn't call the XXX method after uploading the picture?
- If you set
accept, you can try to remove the accept attribute, and then see if the modified method is called. After removing it, the method is called to explain that the file type obtained by accept in the current environment does not match the set accept, and the upload behavior is terminated early. You can make a breakpoint to upload/foundation.js checkFileFormat function to see if the actual value of file.type obtained meets expectations.
- If you set