Input · Upload

Upload

File selection upload

Demos

How to import

import { Avatar, Button, Image, ImagePreview, Radio, RadioGroup, Toast, Tooltip, Upload } from '@fibrous/semi-ui-solid';

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
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload">
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </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
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" showTooltip={false}>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </Button>
        </Upload>
    );
}

When the type is object, you can customize the popup through the renderTooltip function, which receives content (the full file name) and children (the file name element). type and opts configure the tooltip type and the props passed to the popup.

Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Tooltip, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload
            action="https://api.semi.design/upload"
            showTooltip={{
                renderTooltip: (content, children) => (
                    <Tooltip content={content} position="bottom">
                        {children}
                    </Tooltip>
                ),
            }}
        >
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </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
import { For, Show } from 'solid-js';
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, type PromptPositionType, Upload } from '@fibrous/semi-ui-solid';

const action = 'https://api.semi.design/upload';

const positions: PromptPositionType[] = ['right', 'left', 'bottom'];

const getPromptStyle = (pos: PromptPositionType) => ({
    display: 'flex',
    'align-items': 'center',
    color: 'var(--semi-color-text-2)',
    height: '32px',
    ...(pos === 'left' ? { 'margin-right': '10px' } : pos === 'right' ? { 'margin-left': '10px' } : {}),
});

export default function UploadDemo() {
    return (
        <For each={positions}>
            {(pos, index) => (
                <>
                    <Show when={index() > 0}>
                        <div style={{ 'margin-bottom': '12px', 'margin-top': '12px', 'border-bottom': '1px solid var(--semi-color-border)' }} />
                    </Show>
                    <Upload action={action} prompt={<div style={getPromptStyle(pos)}>请上传资格认证材料</div>} promptPosition={pos}>
                        <Button icon={<IconUpload />} theme="light">
                            点击上传
                        </Button>
                    </Upload>
                </>
            )}
        </For>
    );
}

When listType is picture, the reference object at promptPosition is the whole picture wall list

请上传认证材料
dy.jpeg
resso.jpeg
请上传认证材料
dy.jpeg
resso.jpeg
Code
import { For, Show } from 'solid-js';
import { IconPlus } from '@fibrous/semi-icons-solid';
import { type FileItem, type PromptPositionType, Upload } from '@fibrous/semi-ui-solid';

const action = 'https://api.semi.design/upload';

const defaultFileList: 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'];

const getPromptStyle = (pos: PromptPositionType) => ({
    display: 'flex',
    'align-items': 'center',
    color: 'var(--semi-color-text-2)',
    height: '100%',
    ...(pos === 'right' ? { 'margin-left': '10px' } : {}),
});

export default function UploadDemo() {
    return (
        <For each={positions}>
            {(pos, index) => (
                <>
                    <Show when={index() > 0}>
                        <div style={{ 'margin-bottom': '12px', 'margin-top': '12px', 'border-bottom': '1px solid var(--semi-color-border)' }} />
                    </Show>
                    <Upload action={action} prompt={<div style={getPromptStyle(pos)}>请上传认证材料</div>} promptPosition={pos} listType="picture" defaultFileList={defaultFileList}>
                        <IconPlus aria-label="上传图片" size="extra-large" />
                    </Upload>
                </>
            )}
        </For>
    );
}

Click on the avatar to trigger upload

上传头像
Code
import { createSignal } from 'solid-js';
import { IconCamera } from '@fibrous/semi-icons-solid';
import { Avatar, Toast, Upload } from '@fibrous/semi-ui-solid';

const api = 'https://api.semi.design/upload';
const imageOnly = 'image/*';

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)',
};

export default function UploadDemo() {
    const [url, setUrl] = createSignal('/assets/placeholder/avatar-a.svg');

    const onSuccess = () => {
        Toast.success('头像更新成功');
        setUrl('/assets/ttmoment.jpeg');
    };

    return (
        <Upload class="avatar-upload" action={api} onSuccess={onSuccess} accept={imageOnly} showUploadList={false} onError={() => Toast.error('上传失败')}>
            {/* the avatar is the whole content of the upload button, so its alt names the button */}
            <Avatar
                src={url()}
                alt="上传头像"
                style={{ margin: '4px' }}
                hoverMask={
                    <div style={maskStyle}>
                        <IconCamera />
                    </div>
                }
            />
        </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
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

const action = 'https://api.semi.design/upload';
// 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',
};

export default function UploadDemo() {
    return (
        <Upload action={action} data={data} headers={headers}>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </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
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

const action = 'https://api.semi.design/upload';
const imageOnly = 'image/*';
const videoOnly = 'video/*';
const fileLimit = '.pdf,.png,.jpeg';

export default function UploadDemo() {
    return (
        <>
            <Upload action={action} accept={imageOnly} style={{ 'margin-bottom': '12px' }}>
                <Button icon={<IconUpload />} theme="light">
                    上传图片
                </Button>
            </Upload>
            <Upload action={action} accept={videoOnly} style={{ 'margin-bottom': '12px' }}>
                <Button icon={<IconUpload />} theme="light">
                    上传视频
                </Button>
            </Upload>
            <Upload action={action} accept={fileLimit}>
                <Button icon={<IconUpload />} theme="light">
                    上传 PDF, PNG, JPEG
                </Button>
            </Upload>
        </>
    );
}

Upload folder

By passing in directory as true, all files in the folder can be uploaded

Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" directory>
            <Button icon={<IconUpload />} theme="light">
                上传文件夹
            </Button>
        </Upload>
    );
}

Select multiple files at once

You can select multiple files to upload at the same time by setting the multiple attribute.

Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" multiple>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </Button>
        </Upload>
    );
}

Limit the total number of files

Set the limit property to limit the maximum number of files that can be uploaded
When limit is 1, the latest upload always replaces the current one, and the onExceed callback is not triggered

Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload, type UploadOnChangeProps } from '@fibrous/semi-ui-solid';

const limit = 1;

export default function UploadDemo() {
    const onChange = ({ fileList }: UploadOnChangeProps) => {
        console.log(fileList);
    };

    return (
        <Upload action="https://api.semi.design/upload" limit={limit} onChange={onChange}>
            <Button icon={<IconUpload />} theme="light">
                点击上传(最多{limit}项)
            </Button>
        </Upload>
    );
}

When the limit is reached, disable the trigger control rather than Upload, so uploaded files can still be removed.

Code
import { createSignal } from 'solid-js';
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Toast, Upload, type UploadOnChangeProps } from '@fibrous/semi-ui-solid';

const limit = 2;

export default function UploadDemo() {
    const [disabled, setDisabled] = createSignal(false);

    const onChange = ({ fileList }: UploadOnChangeProps) => {
        setDisabled(fileList.length === limit);
    };

    return (
        <Upload action="https://api.semi.design/upload" limit={limit} onExceed={() => Toast.warning(`最多只允许上传${limit}个文件`)} onChange={onChange}>
            <Button icon={<IconUpload />} theme="light" disabled={disabled()}>
                点击上传(最多{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

dyBag.png
dyBag2.jpeg
Code
import { IconPlus } from '@fibrous/semi-icons-solid';
import { type FileItem, Toast, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: 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',
    },
];

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" limit={2} listType="picture" accept="image/*" defaultFileList={defaultFileList} onExceed={() => Toast.warning('最多只允许上传2个文件')}>
            <IconPlus aria-label="上传图片" size="extra-large" />
        </Upload>
    );
}

Limit upload file size

Use the maxSize and minSize properties to customize the file size limits, and set onSizeError to get a callback when a file exceeds them.

Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Toast, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" maxSize={1024} minSize={200} onSizeError={(file) => Toast.error(`${file.name} size invalid`)}>
            <Button icon={<IconUpload />} theme="light">
                点击上传(最小 200KB,最大 1MB)
            </Button>
        </Upload>
    );
}

Custom list operation area

When listType is list, you can customize the list operation area by passing renderFileOperation

已选择文件
dyBag.png130KB
Code
import { IconDelete, IconDownload, IconEyeOpened, IconUpload } from '@fibrous/semi-icons-solid';
import { Button, type FileItem, type RenderFileItemProps, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: FileItem[] = [
    {
        uid: '1',
        name: 'dyBag.png',
        status: 'success',
        size: '130KB',
        preview: true,
        url: '/assets/root-web-sites/edit-bag.jpeg',
    },
];

const renderFileOperation = (fileItem: RenderFileItemProps) => (
    <div style={{ display: 'flex', 'column-gap': '8px', padding: '0 8px' }}>
        <Button aria-label="预览" icon={<IconEyeOpened />} type="tertiary" theme="borderless" size="small" />
        <Button aria-label="下载" icon={<IconDownload />} type="tertiary" theme="borderless" size="small" />
        <Button onClick={() => fileItem.onRemove?.()} aria-label="删除" icon={<IconDelete />} type="tertiary" theme="borderless" size="small" />
    </div>
);

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" defaultFileList={defaultFileList} itemStyle={{ width: '300px' }} renderFileOperation={renderFileOperation}>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </Button>
        </Upload>
    );
}

Custom file list title

When listType is list, you can customize the title area at the top of the file list through fileListTitle. Two forms are supported:

JSX form

When a JSX element is passed, only the title text is replaced and the clear button keeps its default style:

已上传文件
document.pdf130KB
report.xlsx222KB
📁 重要文件
document.pdf130KB
report.xlsx222KB
Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, type FileItem, Upload } from '@fibrous/semi-ui-solid';

const action = 'https://api.semi.design/upload';

const defaultFileList: FileItem[] = [
    {
        uid: '1',
        name: 'document.pdf',
        status: 'success',
        size: '130KB',
    },
    {
        uid: '2',
        name: 'report.xlsx',
        status: 'success',
        size: '222KB',
    },
];

export default function UploadDemo() {
    return (
        <>
            <Upload action={action} defaultFileList={defaultFileList} fileListTitle="已上传文件" style={{ 'margin-bottom': '20px' }}>
                <Button icon={<IconUpload />} theme="light">
                    自定义标题文字
                </Button>
            </Upload>
            <Upload action={action} defaultFileList={defaultFileList} fileListTitle={<span style={{ color: 'var(--semi-color-primary)', 'font-weight': '600' }}>📁 重要文件</span>}>
                <Button icon={<IconUpload />} theme="light">
                    带样式的标题
                </Button>
            </Upload>
        </>
    );
}

Function form

When a function is passed, the whole title area can be customized, including the clear button. The function receives the following arguments:

  • fileList: the current file list
  • onClear: the callback that clears the files
  • clearText: the default text of the clear button (based on the current locale)
📂 共 2 个文件
document.pdf130KB
report.xlsx222KB
已选择 2 个文件
document.pdf130KB
report.xlsx222KB
Code
import { IconClose, IconUpload } from '@fibrous/semi-icons-solid';
import { Button, type FileItem, Upload } from '@fibrous/semi-ui-solid';

const action = 'https://api.semi.design/upload';

const defaultFileList: FileItem[] = [
    {
        uid: '1',
        name: 'document.pdf',
        status: 'success',
        size: '130KB',
    },
    {
        uid: '2',
        name: 'report.xlsx',
        status: 'success',
        size: '222KB',
    },
];

export default function UploadDemo() {
    return (
        <>
            <Upload
                action={action}
                defaultFileList={defaultFileList}
                style={{ 'margin-bottom': '20px' }}
                fileListTitle={({ 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" icon={<IconClose />} onClick={onClear}>
                            {clearText}
                        </Button>
                    </div>
                )}
            >
                <Button icon={<IconUpload />} theme="light">
                    自定义清空按钮样式
                </Button>
            </Upload>
            <Upload
                action={action}
                defaultFileList={defaultFileList}
                fileListTitle={({ 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
                            type="button"
                            onClick={onClear}
                            style={{
                                padding: '0',
                                border: 'none',
                                background: 'none',
                                font: 'inherit',
                                cursor: 'pointer',
                                color: 'var(--semi-color-link)',
                                'font-size': '12px',
                            }}
                        >
                            全部移除
                        </button>
                    </div>
                )}
            >
                <Button icon={<IconUpload />} theme="light">
                    完全自定义标题区域
                </Button>
            </Upload>
        </>
    );
}

Custom preview logic

When listType is list, you can customize the preview logic through previewFile
For example, if you do not need thumbnail previews for image files, you can always return an <IconFile /> from previewFile
If you want to enlarge an image when it is clicked, use the Image component inside previewFile
Or, if you want an extra operation area for the click-to-enlarge preview, you can also combine it with renderFileOperation and place custom elements such as an Icon there

已选择文件
dyBag.png130KB
dyBag2.png130KB
Code
import { IconFile, IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Image, type FileItem, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: FileItem[] = [
    {
        uid: '1',
        name: 'dyBag.png',
        status: 'success',
        size: '130KB',
        url: '/assets/root-web-sites/edit-bag.jpeg',
    },
    {
        uid: '2',
        name: 'dyBag2.png',
        status: 'success',
        size: '130KB',
        url: '/assets/root-web-sites/edit-bag.jpeg',
    },
];

export default function UploadDemo() {
    return (
        <Upload defaultFileList={defaultFileList} action="https://api.semi.design/upload" previewFile={(file) => (file.uid === '1' ? <IconFile size="large" /> : <Image src={file.url} alt="" />)}>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </Button>
        </Upload>
    );
}

An example that combines renderFileOperation with ImagePreview. Clicking the first Icon on the right enlarges the image preview.

已选择文件
dyBag.png130KB
Code
import { createSignal } from 'solid-js';
import { IconDelete, IconDownload, IconExpand, IconUpload } from '@fibrous/semi-icons-solid';
import { Button, type FileItem, ImagePreview, type RenderFileItemProps, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: FileItem[] = [
    {
        uid: '1',
        name: 'dyBag.png',
        status: 'success',
        size: '130KB',
        preview: true,
        url: '/assets/root-web-sites/edit-bag.jpeg',
    },
];

export default function UploadDemo() {
    const [visible, setVisible] = createSignal(false);

    const renderFileOperation = (fileItem: RenderFileItemProps) => (
        <div style={{ display: 'flex', 'column-gap': '8px', padding: '0 8px' }}>
            <Button aria-label="预览" icon={<IconExpand />} type="tertiary" theme="borderless" size="small" onClick={() => setVisible(true)} />
            <Button aria-label="下载" icon={<IconDownload />} type="tertiary" theme="borderless" size="small" />
            <Button aria-label="删除" onClick={() => fileItem.onRemove?.()} icon={<IconDelete />} type="tertiary" theme="borderless" size="small" />
            <ImagePreview src={fileItem.url} visible={visible()} onVisibleChange={(value) => setVisible(value)} />
        </div>
    );

    return (
        <Upload action="https://api.semi.design/upload" defaultFileList={defaultFileList} itemStyle={{ width: '300px' }} renderFileOperation={renderFileOperation}>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </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

已选择文件
dyBag.jpeg130KB
dyBag2.jpeg222KB
上传失败
Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, type FileItem, Upload } from '@fibrous/semi-ui-solid';

const action = 'https://api.semi.design/upload';

const defaultFileList: 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',
    },
];

export default function UploadDemo() {
    return (
        <Upload action={action} defaultFileList={defaultFileList}>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </Button>
        </Upload>
    );
}

Controlled component

When fileList is passed, Upload is used as a controlled component. Listen to the onChange callback and pass a new array object back to Upload as fileList.

已选择文件
dyBag.jpeg130KB
dy.jpeg222KB
Code
import { createSignal } from 'solid-js';
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, type FileItem, Upload, type UploadOnChangeProps } from '@fibrous/semi-ui-solid';

const initList: 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',
    },
];

export default function UploadDemo() {
    const [list, updateList] = createSignal(initList);

    const onChange = ({ fileList, currentFile }: UploadOnChangeProps) => {
        console.log('onChange');
        console.log(fileList);
        console.log(currentFile);
        // 展开得到新数组
        updateList([...fileList]);
    };

    return (
        <Upload action="https://api.semi.design/upload" onChange={onChange} fileList={list()} showRetry={false}>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </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

dy.png
Code
import { IconPlus } from '@fibrous/semi-icons-solid';
import { type FileItem, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: FileItem[] = [
    {
        uid: '1',
        name: 'dy.png',
        status: 'success',
        size: '130KB',
        preview: true,
        url: '/assets/placeholder/avatar-a.svg',
    },
];

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" listType="picture" accept="image/*" multiple defaultFileList={defaultFileList}>
            <IconPlus aria-label="上传图片" size="extra-large" />
        </Upload>
    );
}

Set showPicInfo, you can view the basic information of the picture

music.png
1
brand.png
2
Code
import { IconPlus } from '@fibrous/semi-icons-solid';
import { type FileItem, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: FileItem[] = [
    {
        uid: '1',
        name: 'music.png',
        status: 'success',
        size: '130KB',
        preview: true,
        url: '/assets/placeholder/avatar-b.svg',
    },
    {
        uid: '2',
        name: 'brand.png',
        status: 'success',
        size: '130KB',
        preview: true,
        url: '/assets/placeholder/avatar-b.svg',
    },
];

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" listType="picture" showPicInfo accept="image/*" multiple defaultFileList={defaultFileList}>
            <IconPlus aria-label="上传图片" size="extra-large" />
        </Upload>
    );
}

Photo Wall With Preview

Use the Image component together with the renderThumbnail property to enlarge the picture when it is clicked.

music.png
Code
import { IconPlus } from '@fibrous/semi-icons-solid';
import { Image, type FileItem, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: FileItem[] = [
    {
        uid: '1',
        name: 'music.png',
        status: 'success',
        size: '130KB',
        preview: true,
        url: '/assets/placeholder/avatar-b.svg',
    },
];

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" listType="picture" accept="image/*" multiple defaultFileList={defaultFileList} renderThumbnail={(file) => <Image src={file.url} alt={file.name} />}>
            <IconPlus aria-label="Upload picture" size="extra-large" />
        </Upload>
    );
}

You can customize the preview icon through renderPicPreviewIcon and onPreviewClick. When the replace icon is shown through showReplace, the preview icon is not shown.
To customize the preview or replace feature, turn off the replace feature and listen to the icon click in renderPicPreviewIcon.
onPreviewClick listens to clicks on the container of a single picture.

resso.png
1
Code
import { IconEyeOpened, IconPlus } from '@fibrous/semi-icons-solid';
import { type FileItem, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: 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');
};

export default function UploadDemo() {
    return (
        <>
            <Upload action="https://api.semi.design/upload" listType="picture" showPicInfo accept="image/*" multiple defaultFileList={defaultFileList} onPreviewClick={handlePreview} renderPicPreviewIcon={() => <IconEyeOpened style={{ color: 'var(--semi-color-white)', 'font-size': '24px' }} />}>
                <IconPlus aria-label="上传图片" size="extra-large" />
            </Upload>
        </>
    );
}

Photo Wall Width/Height

Set picHeight and picWidth to set the width and height of the picture wall items uniformly. If you also return an Image component from renderThumbnail to enlarge the picture on click, you need to specify both the width and height of the Image component.

image-1.jpg
点击添加图片
Code
import { IconPlus } from '@fibrous/semi-icons-solid';
import { Image, type FileItem, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: FileItem[] = [
    {
        uid: '1',
        name: 'image-1.jpg',
        status: 'success',
        size: '130KB',
        preview: true,
        url: '/assets/root-web-sites/abstract.jpg',
    },
];

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" listType="picture" accept="image/*" multiple defaultFileList={defaultFileList} picHeight={110} picWidth={200} renderThumbnail={(file) => <Image src={file.url} alt={file.name} width={200} height={110} />}>
            <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


resso.png
1
Code
import { createSignal } from 'solid-js';
import { IconPlus } from '@fibrous/semi-icons-solid';
import { type FileItem, Radio, RadioGroup, Upload, type UploadProps } from '@fibrous/semi-ui-solid';

const defaultFileList: 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');
};

export default function UploadDemo() {
    const [hotSpotLocation, setLocation] = createSignal<UploadProps['hotSpotLocation']>('end');
    return (
        <>
            <RadioGroup value={hotSpotLocation()} type="button" onChange={(event) => setLocation(event.target.value)}>
                <Radio value="start">start</Radio>
                <Radio value="end">end</Radio>
            </RadioGroup>
            <hr />
            <Upload action="https://api.semi.design/upload" listType="picture" showPicInfo accept="image/*" multiple hotSpotLocation={hotSpotLocation()} defaultFileList={defaultFileList} onPreviewClick={handlePreview}>
                <IconPlus aria-label="上传图片" size="extra-large" />
            </Upload>
        </>
    );
}

Disabled

已选择文件
first.png130KB
second.png222KB
Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, type FileItem, Upload } from '@fibrous/semi-ui-solid';

const defaultFileList: 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',
    },
];

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" disabled defaultFileList={defaultFileList}>
            <Button icon={<IconUpload />} theme="light" disabled>
                点击上传
            </Button>
        </Upload>
    );
}

Manually trigger upload

uploadTrigger='custom': after files are selected, the upload will not start automatically. Get the upload component through ref and call its upload method to start it.

Code
import { IconPlus, IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload, type UploadElement } from '@fibrous/semi-ui-solid';

const action = 'https://api.semi.design/upload';

export default function UploadDemo() {
    let uploadRef: UploadElement | undefined;

    const manualUpload = () => {
        uploadRef?.upload();
    };

    return (
        <div>
            <Upload accept="image/gif, image/png, image/jpeg, image/bmp, image/webp" action={action} uploadTrigger="custom" ref={(element) => (uploadRef = element)} onSuccess={(response, file) => console.log(response, file)} onError={(error, file) => console.log(error, file)}>
                <Button icon={<IconPlus />} theme="light" style={{ 'margin-right': '8px' }}>
                    选择文件
                </Button>
            </Upload>
            <Button icon={<IconUpload />} theme="light" onClick={manualUpload}>
                开始上传
            </Button>
        </div>
    );
}

Drag and drop upload

draggable='true', you can use the drag and drop function

点击上传文件或拖拽文件到这里
支持任意类型文件
Code
import { Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return <Upload action="https://api.semi.design/upload" draggable dragMainText="点击上传文件或拖拽文件到这里" dragSubText="支持任意类型文件" />;
}

Use dragIcon, dragMainText and dragSubText to quickly set the content of the drag area.

点击上传文件或拖拽文件到这里
仅支持jpeg、pdf
Code
import { IconBolt } from '@fibrous/semi-icons-solid';
import { Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return <Upload action="https://api.semi.design/upload" dragIcon={<IconBolt />} draggable accept="application/pdf,.jpeg" dragMainText="点击上传文件或拖拽文件到这里" dragSubText="仅支持jpeg、pdf" style={{ 'margin-top': '10px' }} />;
}

You can also pass JSX elements through children to fully customize the content of the drag area.

demo img
Wow, you can really dance.
Code
import { IconBolt } from '@fibrous/semi-icons-solid';
import { Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" dragIcon={<IconBolt />} draggable accept="application/pdf,.jpeg" style={{ 'margin-top': '10px' }}>
            <div class="components-upload-demo-drag-area">
                <img src="/assets/placeholder/avatar-a.svg" height="96" alt="demo img" 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

After addOnPasting is set, files pasted anywhere on the page (the paste event) are added to the file list without clipboard permission. onPastingError is triggered when reading a pasted file fails.

复制截图或文件后,在页面上按 Ctrl/Cmd + V
也可以点击或拖拽上传
Code
import { Toast, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return <Upload action="https://api.semi.design/upload" addOnPasting draggable dragMainText="复制截图或文件后,在页面上按 Ctrl/Cmd + V" dragSubText="也可以点击或拖拽上传" onPastingError={() => Toast.error('读取剪贴板中的文件失败')} />;
}

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, // the validation message of the file; use renderValidateMessage for a node
    shouldUpload: boolean, // Whether to upload. Defaults to true. If false, the fileItem is only shown in the list and no upload is triggered
    autoRemove: boolean, // Whether to remove the file from fileList. Defaults to false
}
Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { type BeforeUploadObjectResult, type BeforeUploadProps, Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    let count = 0;

    const transformFile = (fileInstance: File) => {
        if (count === 0) {
            return new File([fileInstance], 'newFileName', { type: 'image/png' });
        }
        return fileInstance;
    };

    const beforeUpload = ({ file }: BeforeUploadProps) => {
        const result: BeforeUploadObjectResult = count > 0 ? { autoRemove: false, fileInstance: file.fileInstance, shouldUpload: true } : { autoRemove: false, fileInstance: file.fileInstance, status: 'validateFail', shouldUpload: false };
        count = count + 1;
        return result;
    };

    return (
        <Upload action="https://api.semi.design/upload" transformFile={transformFile} beforeUpload={beforeUpload}>
            <Button icon={<IconUpload />} theme="light">
                点击上传(上传前同步校验)
            </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
import { IconUpload } from '@fibrous/semi-icons-solid';
import { type BeforeUploadObjectResult, type BeforeUploadProps, Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    let count = 0;

    const beforeUpload = ({ file }: BeforeUploadProps) => {
        return new Promise<BeforeUploadObjectResult>((resolve, reject) => {
            if (count > 1) {
                const result = {
                    autoRemove: false,
                    shouldUpload: true,
                };
                count = count + 1;
                resolve(result);
            } else {
                const result = {
                    autoRemove: false,
                    fileInstance: file.fileInstance,
                    status: 'validateFail',
                    shouldUpload: false,
                    validateMessage: `第${count + 1}个注定失败`,
                };
                count = count + 1;
                reject(result);
            }
        });
    };

    return (
        <Upload action="https://api.semi.design/upload" beforeUpload={beforeUpload}>
            <Button icon={<IconUpload />} theme="light">
                点击上传(上传前异步校验)
            </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';
    // the validation message of the file; use renderValidateMessage for a node
    validateMessage?: string;
    // whether to remove the file from fileList, defaults to false
    autoRemove?: boolean;
    // the name of the file
    name?: string;
    // the url of the file for preview, usually the storage address returned by the server after it receives the file in this upload request
    url?: string
}
Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { type AfterUploadProps, Button, Upload } from '@fibrous/semi-ui-solid';

const afterUpload = ({ response }: AfterUploadProps) => {
    if (response.status_code === 200) {
        return {
            autoRemove: false,
            status: 'uploadFail',
            validateMessage: '内容不合法',
            name: 'RenameByServer.jpg',
            url: '/assets/root-web-sites/edit-bag.jpeg',
        };
    }
    return {};
};

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" afterUpload={afterUpload}>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </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
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, type UploadCustomRequestArgs, Upload } from '@fibrous/semi-ui-solid';

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);
};

export default function UploadDemo() {
    return (
        <Upload action="https://api.semi.design/upload" customRequest={mockRequest}>
            <Button icon={<IconUpload />} theme="light">
                点击上传
            </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

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.

Set crop={true} to enable the default cropping configuration.

Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload
            action="https://api.semi.design/upload"
            crop
            onSuccess={(response, file) => {
                console.log('上传成功:', response, file);
            }}
        >
            <Button icon={<IconUpload />} theme="light">
                点击上传(启用裁切)
            </Button>
        </Upload>
    );
}

Custom Cropping Configuration

Configure cropping parameters through object form, including aspect ratio, shape, quality, etc.

Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload
            action="https://api.semi.design/upload"
            crop={{
                aspectRatio: 16 / 9,
                shape: 'rect',
                quality: 0.8,
                modalTitle: '裁切图片',
                modalOkText: '确认裁切',
                modalCancelText: '取消',
            }}
            onSuccess={(response, file) => {
                console.log('上传成功:', response, file);
            }}
        >
            <Button icon={<IconUpload />} theme="light">
                点击上传(16:9 裁切)
            </Button>
        </Upload>
    );
}

Round Cropping

Suitable for avatar upload scenarios, set shape: 'round' to enable round cropping.

Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload
            action="https://api.semi.design/upload"
            crop={{
                aspectRatio: 1,
                shape: 'round',
                quality: 0.9,
                modalTitle: '裁切头像',
            }}
            onSuccess={(response, file) => {
                console.log('上传成功:', response, file);
            }}
        >
            <Button icon={<IconUpload />} theme="light">
                点击上传(圆形裁切)
            </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
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload
            action="https://api.semi.design/upload"
            crop={{
                aspectRatio: 1,
                shape: 'round',
            }}
            beforeCrop={(file, fileList) => {
                console.log('beforeCrop:', file, fileList);
                // true continues cropping; false skips it and uploads directly
                return window.confirm('是否裁切图片?');
            }}
            onCropError={(error) => {
                console.error('裁切失败:', error);
            }}
            onSuccess={(response, file) => {
                console.log('上传成功:', response, file);
            }}
        >
            <Button icon={<IconUpload />} theme="light">
                点击上传(裁切前确认)
            </Button>
        </Upload>
    );
}

Drag and Drop Upload with Cropping

Cropping is also triggered when uploading via drag and drop.

Code
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload
            action="https://api.semi.design/upload"
            crop={{
                aspectRatio: 1,
                shape: 'rect',
            }}
            draggable
            onDrop={(_e, files) => {
                console.log('拖拽文件:', files);
            }}
            onSuccess={(response, file) => {
                console.log('上传成功:', response, file);
            }}
        >
            <Button icon={<IconUpload />} theme="light">
                拖拽上传(启用裁切)
            </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
import { IconUpload } from '@fibrous/semi-icons-solid';
import { Button, Upload } from '@fibrous/semi-ui-solid';

export default function UploadDemo() {
    return (
        <Upload
            action="https://api.semi.design/upload"
            crop={{
                aspectRatio: 1,
                shape: 'rect',
            }}
            cropModalProps={{
                width: 800,
                style: { height: '600px' },
                bodyStyle: { height: '500px', 'background-color': '#f5f5f5' },
            }}
            onSuccess={(response, file) => {
                console.log('上传成功:', response, file);
            }}
        >
            <Button icon={<IconUpload />} theme="light">
                自定义弹窗样式
            </Button>
        </Upload>
    );
}

API Reference


Upload

Props

PropertyDescriptionTypeDefault
acceptAccepted file types, written like the accept attribute of input: file extensions such as .jpg or MIME types, separated by commas.string-
actionUpload URL. Required.string-
addOnPastingWhether files in the clipboard are added to the file list on paste, without extra permission.boolean-
afterUploadHook 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-
beforeClearCalled before the list is cleared. Returning false, or a Promise that resolves to false or rejects, blocks the clear.Type(fileList: Array<FileItem>) => boolean | Promise<boolean>-
beforeCropCalled 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>-
beforeRemoveCalled before a file is removed. Returning false, or a Promise that resolves to false or rejects, blocks the removal.Type(file: FileItem, fileList: Array<FileItem>) => boolean | Promise<boolean>-
beforeUploadHook 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-
captureHow media is captured: user or environment. true renders the attribute with an empty value, false omits it.boolean | 'user' | 'environment'-
childrenTrigger content. In draggable mode it replaces the whole default drag area content.JSX.Element-
cropEnables image cropping. true uses the defaults, an object configures the cropper. Selecting, dragging, pasting and replacing all crop.boolean | CropProps-
cropModalPropsProps of the crop Modal. visible, title, okText, cancelText, onOk and onCancel belong to Upload; width defaults to 600.UploadCropModalProps-
customRequestReplaces the built-in XMLHttpRequest. It must call the onProgress, onError and onSuccess it receives to update the state.Type(object: customRequestArgs) => void-
dataExtra parameters sent with the upload, or a function that returns them for a file.TypeRecord<string, any> | ((file: File) => Record<string, unknown>)-
defaultFileListInitial list of uploaded files, uncontrolled. The uid of every item is required and must be unique.TypeArray<FileItem>[]
directoryWhether to upload a folder.boolean-
disabledWhether Upload is disabled. A disabled Upload no longer shows the remove, retry, replace and clear actions.booleanfalse
draggableWhether dragging files to upload is supported.boolean-
dragIconIcon on the left of the drag area. The default icon is shown when omitted.JSX.Element-
dragMainTextMain text of the drag area. The locale text is shown when omitted.JSX.Element-
dragSubTextHelp text of the drag area.JSX.Element-
fileListControlled file list. Passing it makes Upload a controlled component; write a new array back in onChange. The uid of every item is required and must be unique.TypeArray<FileItem>-
fileListTitleTitle area of the file list. A JSX element replaces only the title text and keeps the default clear button. A function replaces the whole title area including the clear button, with fileList, onClear and clearText.TypeJSX.Element | ((props: RenderFileListTitleProps) => JSX.Element)-
fileNameSame as name. Mainly used in Form.Upload to avoid clashing with the name of Field.string-
headersHeaders sent with the upload, or a function that returns them for a file.TypeRecord<string, any> | ((file: File) => Record<string, string>)-
hotSpotLocationPosition of the picture wall add button: start or end.'start' | 'end'"end"
itemStyleInline style of the file cards, as an object with CSS property names as keys.JSX.CSSProperties-
limitMaximum number of files. With 1, the newest file always replaces the current one and onExceed is not called.number-
listTypeHow the file list is displayed: list, picture or none. none renders no file list, only the trigger area.UploadListType"list"
maxSizeMaximum file size in KB.number-
minSizeMinimum file size in KB.number-
multipleWhether several files can be selected at once.booleanfalse
nameField name used for the file when uploading.string-
onAcceptInvalidCalled when received files do not match accept, with those files. This usually happens when a folder with mixed file types is selected or a file of another type is dropped.Type(files: File[]) => void-
onChangeCalled when a file status changes, including uploading, success and failure. The argument is { fileList, currentFile }; currentFile is null for files added with insert.Type(object: OnChangeProps) => void-
onClearCalled when the clear button is clicked.Type() => void-
onCropErrorCalled when cropping an image fails, with the error.Type(error: Error) => void-
onDropCalled 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: Array<File>, fileList: Array<FileItem>) => void-
onErrorCalled when an upload fails. With customRequest, xhr is the object passed to its onError.Type(e: CustomError, file: CustomFile, fileList: Array<FileItem>, xhr: XMLHttpRequest | { status?: number }) => void-
onExceedCalled when the total number of files exceeds limit, with the originally selected files before truncation.Type(fileList: Array<File>) => void-
onFileChangeCalled after files are selected, with the selected files.Type(files: Array<File>) => void-
onOpenFileDialogCalled when the system file dialog opens.Type() => void-
onPastingErrorCalled when addOnPasting is true and a clipboard file cannot be read (getAsFile() returns null or throws).Type(error: Error) => void-
onPreviewClickCalled when a file card is clicked. While present the file cards are clickable and show a preview button; its presence changes the rendering.Type(fileItem: FileItem) => void-
onProgressCalled while uploading, with the percentage, the file and the current file list.Type(percent: number, file: CustomFile, fileList: Array<FileItem>) => void-
onRemoveCalled after a file is removed. currentFile is undefined for an item without a File object, such as one from defaultFileList.Type(currentFile: CustomFile | undefined, fileList: Array<FileItem>, currentFileItem: FileItem) => void-
onRetryCalled when retry is clicked, with the file.Type(fileItem: FileItem) => void-
onSizeErrorCalled when a file size violates maxSize or minSize.Type(file: CustomFile, fileList: Array<FileItem>) => void-
onSuccessCalled after a successful upload, with the server response, the file and the current file list.Type(responseBody: any, file: CustomFile, fileList: Array<FileItem>) => void-
picHeightDisplay height of the pictures in picture mode.string | number-
picWidthDisplay width of the pictures in picture mode.string | number-
previewFileCustom preview that replaces the thumbnail. Only applies in list mode.Type(renderFileItemProps: RenderFileItemProps) => JSX.Element-
promptPrompt text. Unlike content in children, clicking it does not trigger an upload.JSX.Element-
promptPositionPosition 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"
refThe root element, which carries the insert, upload and openFileDialog methods for imperative calls.TypeRef<UploadElement>-
renderFileItemCustom render of a file card, with RenderFileItemProps.Type(renderFileItemProps: RenderFileItemProps) => JSX.Element-
renderFileOperationCustom operation area of a list item. Only applies in list mode.Type(fileItem: RenderFileItemProps) => JSX.Element-
renderPicCloseCustom close button of the picture wall, with class and remove. Only applies in picture mode.Type(renderPicCloseProps: RenderPictureCloseProps) => JSX.Element-
renderPicInfoCustom picture wall information. Only applies in picture mode with showPicInfo set to true.Type(renderFileItemProps: RenderFileItemProps) => JSX.Element-
renderPicPreviewIconCustom preview icon shown on hover in the picture wall. Only applies in picture mode.Type(renderFileItemProps: RenderFileItemProps) => JSX.Element-
renderThumbnailCustom picture wall thumbnail. Only applies in picture mode.Type(renderFileItemProps: RenderFileItemProps) => JSX.Element-
renderValidateMessageCustom validate message of a file card, with RenderFileItemProps. Empty content falls back to the validateMessage of the file. The picture wall shows its validate icon only for a file with a validateMessage, and this replaces the text in the icon's tooltip.Type(fileItem: RenderFileItemProps) => JSX.Element-
showClearIn list mode, whether to show the clear button when limit is not 1 and there is at least one file.booleantrue
showPicInfoWhether to show picture information. Only applies in picture mode.booleanfalse
showReplaceWhether the file card shows a replace button after a successful upload.booleanfalse
showRetryWhether the file card shows a retry button when the upload fails.booleantrue
showTooltipWhether a truncated file name shows a tooltip. An object sets type (tooltip or popover), opts passed to the popup, and renderTooltip for a custom popup.boolean | ShowTooltiptrue
showUploadListWhether to show the file list.booleantrue
timeoutHas no effect; the component does not read it.number-
transformFileCalled after a file is selected and before it is uploaded; returns the File to upload.Type(file: File) => File-
uploadTriggerWhen uploading starts: auto uploads on selection, custom waits for the upload method on the ref.'auto' | 'custom'"auto"
validateMessageValidate message of the whole Upload, as a JSX element.JSX.Element-
validateStatusValidation status, which styles the root element: default, error, warning or success.ValidateStatus-
withCredentialsWhether the upload request carries cookies.booleanfalse

Methods

MethodDescriptionType
insertAdds files at index, or at the end when index is omitted.Type(files: Array<CustomFile>, index?: number) => void
openFileDialogOpens the file dialog.Type() => void
uploadStarts the upload manually. Use it with uploadTrigger set to custom.Type() => void

Undeclared props and events such as class, style and aria-* land on the root element, and ref gives the root element. The root gets role="group" automatically when it has aria-label or aria-labelledby.

Upload.FileCard

Upload.FileCard is the default file card, used to keep the default look inside renderFileItem: <Upload.FileCard {...props} />. data-* and aria-* land on its root element.

Props

PropertyDescriptionTypeDefault
_sizeInvalidInternal flag set by the component when the file size is out of range. Upload uses it to show the invalid size message; do not pass it manually.boolean-
disabledWhether the card is disabled. A disabled card shows no remove, retry or replace button.boolean-
eventxhr event.Event-
fileInstanceThe File object the browser provides, which extends Blob.File-
indexPosition of the file in the list.number-
listTypeDisplay type of the card: list, picture or none.UploadListType-
nameFile name.string-
onPreviewClickCalled when the card is clicked. While present the card is clickable and shows a preview button; its presence changes the rendering.Type() => void-
onRemoveCalled when remove is clicked.Type() => void-
onReplaceCalled when replace is clicked.Type() => void-
onRetryCalled when retry is clicked.Type() => void-
percentUpload progress in percent.number-
picHeightHeight of the picture in picture mode.string | number-
picWidthWidth of the picture in picture mode.string | number-
previewWhether to preview from the url.boolean-
previewFileCustom preview that replaces the thumbnail. Only applies in list mode.Type(fileItem: RenderFileItemProps) => JSX.Element-
renderFileOperationCustom operation area of a list item.Type(fileItem: RenderFileItemProps) => JSX.Element-
renderPicCloseCustom close button of the picture wall, with class and remove. Only applies in picture mode.Type(renderPicCloseProps: RenderPictureCloseProps) => JSX.Element-
renderPicInfoCustom picture wall information. Only applies in picture mode.Type(renderFileItemProps: RenderFileItemProps) => JSX.Element-
renderPicPreviewIconCustom preview icon shown on hover in the picture wall. Only applies in picture mode.Type(renderFileItemProps: RenderFileItemProps) => JSX.Element-
renderThumbnailCustom picture wall thumbnail. Only applies in picture mode.Type(renderFileItemProps: RenderFileItemProps) => JSX.Element-
renderValidateMessageCustom validate message; empty content falls back to validateMessage. The picture wall shows its validate icon only with a validateMessage, and this replaces the text in the icon's tooltip.Type(fileItem: RenderFileItemProps) => JSX.Element-
responseResponse of the xhr. The response body on success, or the matching error on failure.any-
shouldUploadWhether the file should still be uploaded.boolean-
showPicInfoWhether to show picture information. Only applies in picture mode.boolean-
showReplaceWhether to show a replace button after success. The showReplace of the file wins.boolean-
showRetryWhether to show a retry button on failure. The showRetry of the file wins.boolean-
showTooltipWhether a truncated file name shows a tooltip, or the tooltip type and the props passed to it.boolean | ShowTooltip-
sizeFile size in KB.string-
statusFile status: success, uploadFail, validateFail, validating, uploading or wait.FileItemStatus-
styleInline style of the card, as an object with CSS property names as keys.JSX.CSSProperties-
uidUnique identifier of the file. Must be unique in the list.string-
urlFile URL. The picture wall shows the image from it, and previews use it.string-
validateMessageText of the validate message. Use renderValidateMessage for a node.string-

Interfaces

FileItem Interface

interface FileItem {
    event?: Event; // xhr event
    fileInstance?: File; // the File object the browser provides, which extends Blob (https://developer.mozilla.org/en-US/docs/Web/API/File)
    name: string;
    percent?: number; // upload progress in percent
    preview?: boolean; // whether to preview from url
    response?: any; // the xhr response: the response body on success, the corresponding error on failure
    shouldUpload?: boolean; // whether to continue uploading
    showReplace?: boolean; // controls whether this file shows the replace button
    showRetry?: boolean; // controls whether this file shows the retry button
    size: string; // file size in KB
    status: 'success' | 'uploadFail' | 'validateFail' | 'validating' | 'uploading' | 'wait';
    uid: string; // unique identifier of the file. Generated automatically for files selected through upload; for defaultFileList, make sure it is unique
    url?: string;
    validateMessage?: string; // the validation message; use renderValidateMessage for a node
}

FileItem has only the fields above; writing an undeclared field is a type error.

RenderFileItemProps Interface

The arguments received by renderFileItem, renderThumbnail, renderPicInfo, renderPicPreviewIcon, renderFileOperation, renderValidateMessage and previewFile. They add the file card properties on top of FileItem.

interface RenderFileItemProps extends FileItem {
    index?: number; // position of the file in the list
    listType?: 'picture' | 'list' | 'none';
    disabled?: boolean;
    style?: JSX.CSSProperties; // from itemStyle
    showRetry?: boolean;
    showReplace?: boolean;
    showPicInfo?: boolean;
    showTooltip?: boolean | ShowTooltip;
    picWidth?: string | number;
    picHeight?: string | number;
    onRemove?: () => void; // remove this file
    onRetry?: () => void; // upload this file again
    onReplace?: () => void; // replace this file
    onPreviewClick?: () => void; // called when the file card is clicked
    previewFile?: (renderProps: RenderFileItemProps) => JSX.Element;
    renderPicInfo?: (renderProps: RenderFileItemProps) => JSX.Element;
    renderPicPreviewIcon?: (renderProps: RenderFileItemProps) => JSX.Element;
    renderPicClose?: (renderPicCloseProps: { class: string; remove: (e: MouseEvent) => void }) => JSX.Element;
    renderThumbnail?: (renderProps: RenderFileItemProps) => JSX.Element;
    renderFileOperation?: (renderProps: RenderFileItemProps) => JSX.Element;
    renderValidateMessage?: (renderProps: RenderFileItemProps) => JSX.Element; // empty content falls back to validateMessage
}

RenderFileListTitleProps Interface

The argument type when fileListTitle is passed a function:

interface RenderFileListTitleProps {
    fileList: Array<FileItem>; // the current file list
    onClear: () => void; // the callback that clears the files
    clearText: string; // the default text of the clear button (based on the current locale)
}

CropProps Interface

Configuration object accepted by the crop prop:

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

Some internal methods provided by Upload can be accessed through the ref of the root element:

NameDescriptionType
insertUpload file, when index is passed, it will be inserted at the specified position, if not passed, it will be inserted at the end(files: Array<File>, index?: number) => void
uploadStart upload manually, use with uploadTrigger="custom"() => void
openFileDialogOpen the file selection dialog() => void

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 (native disabled or aria-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 disabled to that control as well. When limit is reached, disable only that control and not Upload, so users can still remove uploaded files
  • When the root element has aria-label or aria-labelledby, it gets role="group" automatically; a role you pass yourself wins
  • Add role="list" to the file list and describe it with aria-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
  • 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

These are the component's internal Sass variables and cannot be overridden. To customize styles, override the --semi-* CSS variables (see the Design Token page) or write unlayered CSS rules.
Sass variableValueUsage
$color-upload-textvar(--semi-color-text-0)上传文件卡片等默认文本颜色
$color-upload_assist-textvar(--semi-color-text-2)上传文件列表标题及文件大小文本颜色
$color-upload-bordervar(--semi-color-border)图片墙添加按钮及拖拽区域描边颜色
$color-upload_card-bg-hovervar(--semi-color-fill-1)上传文件卡片背景色 - 悬浮
$color-upload_card-bgvar(--semi-color-fill-0)上传文件卡片背景色 - 默认
$color-upload_card_fail-bg-hovervar(--semi-color-danger-light-hover)上传失败文件卡片背景色 - 悬浮
$color-upload_card_fail-bgvar(--semi-color-danger-light-default)上传失败文件卡片背景色 - 默认
$color-upload_clear-textvar(--semi-color-primary)上传清空按钮文本颜色
$color-upload_drag_area-bg-hovervar(--semi-color-primary-light-default)上传可拖拽区域背景颜色 - 悬浮
$color-upload_drag_area-border-hovervar(--semi-color-primary)上传可拖拽区域描边颜色 - 悬浮
$color-upload_drag_area_disabled-textvar(--semi-color-disabled-text)上传可拖拽区域禁用文本颜色
$color-upload_drag_area-bgvar(--semi-color-tertiary-light-default)上传可拖拽区域背景颜色 - 默认
$color-upload_drag_area_iconvar(--semi-color-primary)上传可拖拽区域图标颜色
$color-upload_drag_area_tips-textvar(--semi-color-primary)上传可拖拽区域提示文本颜色
$color-upload_drag_area_main-text-defaultvar(--semi-color-text-0)上传可拖拽区主要提示文本颜色 - 默认
$color-upload_drag_area_main-text-hovervar(--semi-color-text-0)上传可拖拽区主要提示文本颜色 - 悬浮
$color-upload_drag_area_main-text-activevar(--semi-color-text-0)上传可拖拽区主要提示文本颜色 - 按下
$color-upload_drag_area_sub-text-defaultvar(--semi-color-text-0)上传可拖拽区次要提示文本颜色 - 默认
$color-upload_drag_area_sub-text-hovervar(--semi-color-text-0)上传可拖拽区次要提示文本颜色 - 悬浮
$color-upload_drag_area_sub-text-activevar(--semi-color-text-0)上传可拖拽区次要提示文本颜色 - 按下
$color-upload_file_card_fail_info-textvar(--semi-color-danger)上传文件卡片失败提示信息文本颜色
$color-upload_file_card_preview_placeholder-bgvar(--semi-grey-3)文件卡片默认预览背景颜色
$color-upload_file_card_preview_placeholder-textvar(--semi-white)文件卡片默认预览图颜色
$color-upload_file_card_retry-bgvar(--semi-color-white)图片墙上传卡片重新上传按钮背景颜色
$color-upload_file_card_retry-textvar(--semi-color-primary)图片墙上传卡片重新上传按钮文本颜色
$color-upload-iconvar(--semi-color-tertiary)图片墙上传图标加号颜色
$color-upload_pic_add-bg-activevar(--semi-color-fill-2)图片墙上传背景色 - 按下
$color-upload_pic_add-bg-hovervar(--semi-color-fill-1)图片墙上传背景色 - 悬浮
$color-upload_pic_add-bgvar(--semi-color-fill-0)图片墙上传背景色 - 默认
$color-upload_picture_file_card_loading_error-iconvar(--semi-color-danger)图片墙上传卡片加载及失败状态图标颜色
$color-upload_picture_file_card_error-bordervar(--semi-color-danger)图片墙上传卡片失败状态描边颜色
$color-upload_picture_file_card_pic_info-textvar(--semi-color-white)图片墙图片信息(序号)文字颜色
$color-upload_picture_file_card_close-iconvar(--semi-color-white)图片墙关闭图标颜色
$color-upload_picture_file_card_hover-bgvar(--semi-color-overlay-bg)图片墙预览悬浮背景色
$color-upload_preview-iconvar(--semi-color-text-2)上传文件卡片文本颜色
$color-upload_retry-textvar(--semi-color-primary)上传文件卡片重新上传按钮文本颜色
$color-upload_replace-textvar(--semi-color-white)图片墙上传卡片替换按钮文本颜色
$height-upload_file_card52px上传文件卡片高度
$width-upload_file_card250px上传文件卡片宽度
$height-upload_file_pic_card96px图片墙上传卡片高度
$width-upload_file_pic_card96px图片墙上传卡片宽度
$width-upload_file_card_preview36px文件卡片预览图标宽度
$height-upload_file_card_preview36px文件卡片预览图标高度
$width-upload_file_card_preview_img36px文件卡片预览图片宽度
$width-upload_file_card-icon11px文件卡片图标宽度
$width-upload_picture_add-border2px图片墙添加按钮描边宽度
$width-upload_picture_file_card_img96px图片墙上传卡片宽度
$width-upload_picture_file_card_close16px图片墙上传卡片删除按钮图标宽度
$width-upload_file_card_retry24px重新上传按钮宽度
$width-upload_file_card_retry-icon13px重新上传按钮图标宽度
$width-upload_picture_file_card_loading-icon14px上传加载 spin 宽度
$width-upload_drag_area-border2px可拖拽上传描边宽度
$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-marginTop4px上传文件卡片进度顶部外边距
$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-top8px图片墙上传卡片删除按钮顶部位置
$spacing-upload_picture_file_card_close-right8px图片墙上传卡片删除右侧位置
$spacing-upload_picture_file_card_loading_error-bottom6px图片墙上传卡片加载中图标底部位置
$spacing-upload_picture_file_card_loading_error-right6px图片墙上传卡片报错图标底部位置
$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_cardvar(--semi-border-radius-medium)上传文件卡片圆角
$radius-upload_file_card_previewvar(--semi-border-radius-small)上传文件卡片预览图圆角
$radius-upload_picture_addvar(--semi-border-radius-small)图片墙上传文件添加按钮圆角
$radius-upload_picture_file_card_imgvar(--semi-border-radius-small)图片墙上传卡片圆角
$radius-upload_picture_file_card_closevar(--semi-border-radius-circle)图片墙上传卡片删除按钮圆角
$radius-upload_file_card_retryvar(--semi-border-radius-circle)上传文件卡片重新上传圆角
$radius-upload_drag_areavar(--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-fontWeight600可拖拽上传提示文本字重
$font-upload_picture_file_card_pic_info-fontSize12px图片墙图片信息字体大小
$font-upload_picture_file_card_pic_info-fontWeight600图片墙图片信息文本字重

FAQ

  • When will the retry button appear?
    • When showRetry is 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 will the replace button appear?
    • When showReplace is true and the current file status is uploaded, the replace button will be displayed.
  • 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.