# 上传

- 页面: https://jiguang132.com/zh/resources/ant-design/docs/upload
- 资源: Ant Design (https://jiguang132.com/zh/resources/ant-design.md)
- 全部指南: https://jiguang132.com/zh/resources/ant-design/docs.md

文件选择上传和拖拽上传控件。


## 何时使用 {#when-to-use}

上传是将信息（网页、文字、图片、视频等）通过网页或者上传工具发布到远程服务器上的过程。

- 当需要上传一个或一些文件时。
- 当需要展现上传的进度时。
- 当需要使用拖拽交互时。

## 代码演示 {#examples}


- 点击上传 · `basic`
- 用户头像 · `avatar`
- 已上传的文件列表 · `defaultFileList`
- 照片墙 · `picture-card`
- 圆形照片墙 · `picture-circle`
- 完全控制的上传列表 · `fileList`
- 拖拽上传 · `drag`
- 粘贴上传 · `paste`
- 文件夹上传 · `directory`
- 手动上传 · `upload-manually`
- 只上传 png 图片 · `upload-png-only`
- 图片列表样式 · `picture-style`
- 自定义预览 · `preview-file`
- 限制数量 · `max-count`
- 上传前转换文件 · `transform-file`
- 阿里云 OSS · `upload-with-aliyun-oss`

- 自定义交互图标和文件信息 · `upload-custom-action-icon`
- 上传列表拖拽排序 · `drag-sorting`
- 上传前裁切图片 · `crop-image`
- 自定义进度条样式 · `customize-progress-bar`
- 自定义语义结构的样式和类 · `style-class`



## API

通用属性参考：[通用属性](#jguang-common-props)

| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| accept | 接受上传的文件类型，详见 [input accept Attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept) | string \| [AcceptObject](#acceptobject) | - |  | 6.4.0 |
| action | 上传的地址 | string \| (file) => Promise&lt;string> | - |  | × |
| beforeUpload | 上传文件之前的钩子，参数为上传的文件，若返回 `false` 则停止上传。支持返回一个 Promise 对象，Promise 对象 reject 时则停止上传，resolve 时开始上传（ resolve 传入 `File` 或 `Blob` 对象则上传 resolve 传入对象）；也可以返回 `Upload.LIST_IGNORE`，此时列表中将不展示此文件。 **注意：IE9 不支持该方法** | (file: [RcFile](#rcfile), fileList: [RcFile[]](#rcfile)) => boolean \| Promise&lt;File> \| `Upload.LIST_IGNORE` | - |  | × |
| customRequest | 通过覆盖默认的上传行为，可以自定义自己的上传实现 | ( options: [RequestOptions](#request-options), info: { defaultRequest: (option: [RequestOptions](#request-options)) => void; } ) => void | - | defaultRequest: 5.28.0 | 5.27.0 |
| classNames | 用于自定义组件内部各语义化结构的 class，支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - |  | 6.0.0 |
| data | 上传所需额外参数或返回上传额外参数的方法 | object\|(file) => object \| Promise&lt;object> | - |  | × |
| defaultFileList | 默认已经上传的文件列表 | object\[] | - |  | × |
| directory | 支持上传文件夹（[caniuse](https://caniuse.com/#feat=input-file-directory)） | boolean | false |  | × |
| disabled | 是否禁用。对于自定义 Upload children 时，请同时将 `disabled` 属性传给 child node，以确保禁用状态的渲染效果保持一致 | boolean | false |  | × |
| fileList | 已经上传的文件列表（受控），使用此参数时，如果遇到 `onChange` 只调用一次的问题，请参考 [#2423](https://github.com/ant-design/ant-design/issues/2423) | [UploadFile](#uploadfile)\[] | - |  | × |
| headers | 设置上传的请求头部，IE10 以上有效 | object | - |  | × |
| iconRender | 自定义显示 icon | (file: UploadFile, listType?: UploadListType) => ReactNode | - |  | × |
| isImageUrl | 自定义缩略图是否使用 &lt;img /> 标签进行显示 | (file: UploadFile) => boolean | [(内部实现)](https://github.com/ant-design/ant-design/blob/4ad5830eecfb87471cd8ac588c5d992862b70770/components/upload/utils.tsx#L47-L68) |  | × |
| itemRender | 自定义上传列表项 | (originNode: ReactElement, file: UploadFile, fileList: object\[], actions: { download: function, preview: function, remove: function }) => React.ReactNode | - | 4.16.0 | × |
| listType | 上传列表的内建样式，支持四种基本样式 `text`, `picture`, `picture-card` 和 `picture-circle` | string | `text` | `picture-circle`(5.2.0+) | × |
| maxCount | 限制上传数量。当为 1 时，始终用最新上传的文件代替当前文件 | number | - | 4.10.0 | × |
| method | 上传请求的 http method | string | `post` |  | × |
| multiple | 是否支持多选文件，`ie10+` 支持。开启后按住 ctrl 可选择多个文件 | boolean | false |  | × |
| name | 发到后台的文件参数名 | string | `file` |  | × |
| openFileDialogOnClick | 点击打开文件对话框 | boolean | true |  | × |
| pastable | 是否支持粘贴文件 | boolean | false | 5.25.0 | × |
| previewFile | 自定义文件预览逻辑 | (file: File \| Blob) => Promise&lt;dataURL: string> | - |  | × |
| progress | 自定义进度条样式 | [ProgressProps](/components/progress#api)（仅支持 `type="line"`） | { strokeWidth: 2, showInfo: false } | 4.3.0 | 6.4.0 |
| showUploadList | 是否展示文件列表, 可设为一个对象，用于单独设定 `extra`(5.20.0+), `showPreviewIcon`, `showRemoveIcon`, `showDownloadIcon`, `removeIcon` 和 `downloadIcon` | boolean \| { extra?: ReactNode \| (file: UploadFile) => ReactNode, showPreviewIcon?: boolean \| (file: UploadFile) => boolean, showDownloadIcon?: boolean \| (file: UploadFile) => boolean, showRemoveIcon?: boolean \| (file: UploadFile) => boolean, previewIcon?: ReactNode \| (file: UploadFile) => ReactNode, removeIcon?: ReactNode \| (file: UploadFile) => ReactNode, downloadIcon?: ReactNode \| (file: UploadFile) => ReactNode } | true | `extra`: 5.20.0, `showPreviewIcon` function: 5.21.0, `showRemoveIcon` function: 5.21.0, `showDownloadIcon` function: 5.21.0 | × |
| styles | 用于自定义组件内部各语义化结构的行内 style，支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - |  | 6.0.0 |
| withCredentials | 上传请求时是否携带 cookie | boolean | false |  | × |
| onChange | 上传文件改变时的回调，上传每个阶段都会触发该事件。详见 [onChange](#onchange) | function | - |  | × |
| onDrop | 当文件被拖入上传区域时执行的回调功能 | (event: React.DragEvent) => void | - | 4.16.0 | × |
| onDownload | 点击下载文件时的回调，如果没有指定，则默认跳转到文件 url 对应的标签页 | function(file): void | (跳转新标签页) |  | × |
| onPreview | 点击文件链接或预览图标时的回调 | function(file) | - |  | × |
| onRemove | 点击移除文件时的回调，返回值为 false 时不移除。支持返回一个 Promise 对象，Promise 对象 resolve(false) 或 reject 时不移除 | function(file): boolean \| Promise | - |  | × |

## Interface

### RcFile

继承自 [File](https://developer.mozilla.org/zh-CN/docs/Web/API/File)。

| 参数             | 说明                           | 类型   | 默认值 | 版本 |
| ---------------- | ------------------------------ | ------ | ------ | ---- |
| uid              | 唯一标识符，不设置时会自动生成 | string | -      | -    |
| lastModifiedDate | 上次修改文件的日期和时间       | date   | -      | -    |

### UploadFile

继承自 [File](https://developer.mozilla.org/zh-CN/docs/Web/API/File)，附带额外属性用于渲染。

| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| crossOrigin | CORS 属性设置 | `'anonymous'` \| `'use-credentials'` \| `''` | - | 4.20.0 |
| name | 文件名 | string | - | - |
| percent | 上传进度 | number | - | - |
| status | 上传状态，不同状态展示颜色也会有所不同 | `error` \| `done` \| `uploading` \| `removed` | - | - |
| thumbUrl | 缩略图地址 | string | - | - |
| uid | 唯一标识符，不设置时会自动生成 | string | - | - |
| url | 下载地址 | string | - | - |

### RequestOptions {#request-options}

| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| action | 上传的地址 | string | - | - |
| data | 上传所需额外参数或返回上传额外参数的方法 | Record<string, unknown> | - | - |
| filename | 文件名 | string | - | - |
| file | 文件信息 | [UploadFile](#uploadfile) | - | - |
| withCredentials | 上传请求时是否携带 cookie | boolean | - | - |
| headers | 上传的请求头部 | Record<string, string> | - | - |
| method | 上传请求的 http method | string | - | - |
| onProgress | 上传进度回调 | (event: object, file: UploadFile) => void | - | - |
| onError | 上传失败回调 | (event: object, body?: object) => void | - | - |
| onSuccess | 上传成功回调 | (body: object, fileOrXhr?: UploadFile \| XMLHttpRequest) => void | - | - |

### onChange

> 💡 上传中、完成、失败都会调用这个函数。

文件状态改变的回调，返回为：

```jsx
{
  file: { /* ... */ },
  fileList: [ /* ... */ ],
  event: { /* ... */ },
}
```

1. `file` 当前操作的文件对象。

   ```jsx
   {
      uid: 'uid',      // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
      name: 'xx.png',   // 文件名
      status: 'done' | 'uploading' | 'error' | 'removed' , //  beforeUpload 拦截的文件没有 status 状态属性
      response: '{"status": "success"}', // 服务端响应内容
      linkProps: '{"download": "image"}', // 下载链接额外的 HTML 属性
   }
   ```

2. `fileList` 当前的文件列表。

3. `event` 上传中的服务端响应内容，包含了上传进度等信息，高级浏览器支持。

### AcceptObject

```typescript
{
  format: string;
  filter?: 'native' | ((file: RcFile) => boolean);
}
```

用于配置文件类型接受的规则对象。

| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| format | 接受的文件类型，与原生 input accept 属性相同，支持 MIME 类型、文件扩展名等格式。详见 [input accept Attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept) | string | - |  |
| filter | 文件过滤规则。设置为 `'native'` 时使用浏览器原生过滤行为；设置为函数时可以自定义过滤逻辑，函数返回 `true` 表示接受该文件，返回 `false` 表示拒绝 | `'native'` \| `(file: RcFile) => boolean` | - |  |

## Semantic DOM

| 语义节点 | 原生说明 | 版本 |
| --- | --- | --- |
| `root` | 根元素容器，包含布局样式、禁用状态文字颜色、用户选择控制、鼠标样式等基础样式 | 6.0.0 |
| `list` | 文件列表容器，包含布局排列、过渡动画、间距控制等样式 | 6.0.0 |
| `item` | 文件项元素，包含内边距、背景色、边框样式、悬停效果、状态颜色、过渡动画等样式 | 6.0.0 |
| `trigger` | 上传按钮容器，包含按钮样式、禁用状态、隐藏控制等样式 | 6.3.0 |

语义说明来源: `vendor/components/upload/demo/_semantic.tsx`

## 主题变量（Design Token）{#design-token}

类型、继承关系和原生令牌声明保持固定源码原文；默认值由原生主题计算，并可能受 ConfigProvider 覆盖。本表不伪造静态默认值。

| 令牌 | 类型 | 原生说明 |
| --- | --- | --- |
| `actionsColor` | `string` | 操作按扭颜色 |
| `pictureCardSize` | `number` | 卡片类型文件列表项的尺寸（对 picture-card 和 picture-circle 生效） |

声明来源: `vendor/components/upload/style/index.ts`

```ts
import type { CSSObject } from '@ant-design/cssinjs';

import { resetComponent } from '../../style';

import { genCollapseMotion } from '../../style/motion';

import type { FullToken, GenerateStyle, GetDefaultToken } from '../../theme/internal';

import { genStyleHooks, mergeToken } from '../../theme/internal';

import genDraggerStyle from './dragger';

import genListStyle from './list';

import genMotionStyle from './motion';

import { genPictureCardStyle, genPictureStyle } from './picture';

import genRtlStyle from './rtl';

export interface ComponentToken {
  /**
   * @desc 操作按扭颜色
   * @descEN Action button color
   */
  actionsColor: string;
  /**
   * @desc 卡片类型文件列表项的尺寸（对 picture-card 和 picture-circle 生效）
   * @descEN Size of list items in card type (affects both picture-card and picture-circle)
   */
  pictureCardSize: number;
}

export interface UploadToken extends FullToken<'Upload'> {
  uploadThumbnailSize: number | string;
  uploadProgressOffset: number | string;
  uploadPicCardSize: number | string;
}
```

## FAQ

### 服务端如何实现？ {#faq-server-implement}

- 服务端上传接口实现可以参考 [jQuery-File-Upload](https://github.com/blueimp/jQuery-File-Upload/wiki#server-side)。
- 如果要做本地 mock 可以参考这个 [express 的例子](https://github.com/react-component/upload/blob/211979fdaa2c7896b6496df7061a0cfc0fc5434e/server.js)。

### 如何显示下载链接？ {#faq-show-download-link}

请使用 `fileList` 属性设置数组项的 `url` 属性进行展示控制。

### `customRequest` 怎么使用？ {#faq-custom-request}

请参考 <https://github.com/react-component/upload#customrequest>。

### 为何 `fileList` 受控时，上传不在列表中的文件不会触发 `onChange` 后续的 `status` 更新事件？ {#faq-filelist-controlled-status}

`onChange` 事件仅会作用于在列表中的文件，因而 `fileList` 不存在对应文件时后续事件会被忽略。请注意，在 `4.13.0` 版本之前受控状态存在 bug 导致不在列表中的文件也会触发。

### `onChange` 为什么有时候返回 File 有时候返回 { originFileObj: File }？ {#faq-on-change-return-type}

历史原因，在 `beforeUpload` 返回 `false` 时，会返回 `File` 对象。在下个大版本我们会统一返回 `{ originFileObj: File }` 对象。当前版本已经兼容所有场景下 `info.file.originFileObj` 获取原 `File` 写法。你可以提前切换。

### 为何有时 Chrome 点击 Upload 无法弹出文件选择框？ {#faq-chrome-file-picker}

与 `antd` 无关，原生上传也会失败。请重启 `Chrome` 浏览器，让其完成升级工作。

<img alt="点击 Chrome 重启启动按钮" src="https://github.com/ant-design/ant-design/assets/507615/1509b25f-4cd3-41b2-9415-90394ad08273" width="800" />

相关 `issue`：

- [#48007](https://github.com/ant-design/ant-design/issues/48007)
- [#32672](https://github.com/ant-design/ant-design/issues/32672)
- [#32913](https://github.com/ant-design/ant-design/issues/32913)
- [#33988](https://github.com/ant-design/ant-design/issues/33988)

### 文件夹上传在 Safari 仍然可以选中文件? {#faq-safari-folder-upload}

组件内部是以 `directory`、`webkitdirectory` 属性控制 input 来实现文件夹选择的, 但似乎在 Safari 的实现中，[并不会阻止用户选择文件](https://stackoverflow.com/q/55649945/3040605)。可以通过 `accept` 配置来解决此问题，例如：

```tsx
accept = {
  // 不允许选择任何文件
  format: `.${'n'.repeat(100)}`,
  // 当选择文件夹后，接受所有文件夹内的文件
  filter: () => true,
};
```


## 原生通用属性 {#jguang-common-props}


> Tips: 以下通用属性适用于 antd 大部分组件，不支持的组件会单独说明。

| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| style | 自定义样式 | CSSProperties | - |
| className | 自定义类名 | string | - |
| rootClassName | 添加在组件最外层的 className | string | - |
| autoFocus | 自动获取焦点，仅对表单类、链接、交互容器等可聚焦元素生效 | boolean | false |


## 安装并复现示例

```bash
npm install antd@6.6.5 @ant-design/icons@6.3.4 dayjs@1.11.23
```

使用 ConfigProvider 和原生 App，并单独配置 dayjs 语言。每个示例在查看代码中列出完整源码文件和额外固定依赖。示例名称用于选择演示，不是组件通用属性。主题、语言与 SSR 初始化见资源安装指南。

## 原生类型参考

源码查看器包含未修改的原生实现和以下声明文件，继承类型仍位于原生包中。代码中的英文注释保留为源码参考。

- `vendor/components/upload/Dragger.tsx`
- `vendor/components/upload/Upload.tsx`
- `vendor/components/upload/UploadList/ListItem.tsx`
- `vendor/components/upload/UploadList/index.tsx`
- `vendor/components/upload/index.tsx`
- `vendor/components/upload/interface.ts`
- `vendor/components/upload/style/index.ts`

## 来源与许可

https://github.com/ant-design/ant-design/tree/4a39f54842eade4e565ab336ef6097cd7e723cdd

保留原生中英文正文与可执行示例；官网专用的嵌入章节和令牌表格在本地展开。Ant Design 使用 MIT 许可，另列依赖的许可证也需保留。上传预览禁止向外发起请求，不提供后端服务。

## 本地示例适配

- `authored/demos/upload/crop-image.tsx`: 按 ConfigProvider 的语言显式设置原生裁剪器标题、重置与操作文案，不依赖浏览器语言。 原始对照文件: `vendor/components/upload/demo/crop-image.tsx`.
- `authored/demos/upload/preview-file.tsx`: 缩略图服务不可用或响应无效时，显示原生警告并回退到无缩略图，不误报上传成功。 原始对照文件: `vendor/components/upload/demo/preview-file.tsx`.
- `authored/demos/upload/drag-sorting.tsx`: 忽略上传列表外的拖放和已不存在的文件标识，避免把无效负索引传给 arrayMove 导致误排序。 原始对照文件: `vendor/components/upload/demo/drag-sorting.tsx`.

复制示例清单中的适配 sourceFiles；上游对照源码保持不变。详见 LOCAL_CHANGES.md。

---

JGuang 全部资源索引: https://jiguang132.com/llms.txt
