ant-design Upload 组件入门:从「点击上传」Demo 到源码级解析
【免费下载链接】ant-designAn enterprise-class UI design language and React UI library项目地址: https://gitcode.com/gh_mirrors/antde/ant-design
上传是 Web 表单类交互中最常见的需求之一:把本地文件通过网络提交到远程服务器,并实时反馈进度与结果。ant-design(Ant Design)作为企业级 React UI 组件库,在 components/upload/index.jsx 中封装了Upload组件,而components/upload/demo/basic.md正是它最经典的「点击上传」示例:用户点击按钮弹出文件选择框,选中文件后即自动发起上传。读完本篇,你将掌握Upload组件的最小可用配置、核心参数与回调的使用方法,并能结合源码理解文件状态流转与底层实现原理。
一、经典「点击上传」Demo 解读
1.1 最小可用代码
components/upload/demo/basic.md给出了 Upload 组件最经典、最简洁的用法——点击按钮触发文件选择,选择后自动上传:
import { Upload, message, Button, Icon } from 'antd'; const props = { name: 'file', action: '/upload.do', headers: { authorization: 'authorization-text', }, onChange(info) { if (info.file.status !== 'uploading') { console.log(info.file, info.fileList); } if (info.file.status === 'done') { message.success(`${info.file.name} 上传成功。`); } else if (info.file.status === 'error') { message.error(`${info.file.name} 上传失败。`); } } }; ReactDOM.render( <Upload {...props}> <Button type="ghost"> <Icon type="upload" /> 点击上传 </Button> </Upload> , mountNode);这段代码展示了 Upload 的核心工作方式:
action:必选参数,指定文件上传的服务端地址(示例中的/upload.do为示意地址,实际开发需替换为真实接口);name:上传文件的字段名,服务端应通过该字段名接收文件,默认值为file;headers:自定义请求头,示例中携带了authorization鉴权信息;onChange:监听文件状态变化,根据info.file.status区分done(成功)与error(失败),配合message组件给出用户反馈。
1.2 从 UI 结构理解组件形态
从 index.jsx 的 render 方法 可以看到,type === 'select'(默认)时组件渲染结构为:
<span className={className}> <div className="ant-upload ant-upload-select ant-upload-select-text"> <Upload> // 来自 rc-upload,内部隐藏 input[type=file] {children} // 这里即 <Button>点击上传</Button> </Upload> </div> {uploadList} // showUploadList 为 true 时渲染文件列表 </span>也就是说,Upload的子节点只是触发器的外观,真正负责文件选择的<input type="file">由底层 rc-upload 库隐藏渲染,点击按钮会冒泡触发其原生文件选择框。用户选中文件后,组件立即自动发起上传请求,无需额外调用提交方法。
二、Upload 核心 API 全解析
components/upload/index.md的 API 表格与 index.jsx 的 getDefaultProps 相互印证,以下是完整参数说明:
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| name | 上传文件的字段名,服务端以此接收文件 | String | file |
| action | 必选,上传的地址 | String | 无 |
| data | 上传时附带的额外参数(Object),会随请求一起提交 | Object | 无 |
| headers | 自定义请求头,IE10 以上有效 | Object | 无 |
| showUploadList | 是否展示已上传文件列表 | Boolean | true |
| multiple | 是否支持多选文件,ie10+支持,开启后按住 ctrl 可选择多个文件 | Boolean | false |
| accept | 接受的文件类型,详见 input 的 accept 属性 | String | 无 |
| beforeUpload | 上传前的钩子,参数为待上传的文件;返回false或 Promise 则停止上传(不支持老 IE) | Function | 无 |
| onChange | 文件状态改变时的回调 | Function | 无 |
| listType | 上传列表的内建样式,支持text或picture | String | 'text' |
| className | 自定义类名 | String | 无 |
注:源码中
listType实际还支持picture-card(见 uploadList.jsx 的分支判断),对应「照片墙」样式;getDefaultProps中data: {}、onChange: noop、beforeUpload: T(恒返回 true)等默认值也与表格一致。
2.1 onChange 回调的返回值
onChange在文件状态改变时触发,返回对象结构为:
{ file: { ... }, fileList: [ ... ], event: { ... } }其中:
file:当前操作的文件对象,关键字段如下:
{ uid: 'uid', // 文件唯一标识,建议设置为负数,防止和内部产生的 id 冲突 name: 'xx.png', // 文件名 status: 'done', // 状态有:uploading done error removed response: '{"status":"success"}' // 服务端响应内容 }当multiple开启时,此参数为对象数组[file, ...]。
fileList:当前的文件列表。event:上传过程中的服务端响应内容,包含上传进度等信息(高级浏览器支持)。
2.2 文件状态流转与源码印证
在 index.jsx 中可以清晰看到文件对象的生命周期:
uploading:onStart中调用fileToObject将原生 File 转为组件内部对象并置为uploading(index.jsx#L64-L89);done:onSuccess中将targetItem.status置为done并写入response(index.jsx#L113-L131);error:onError中记录error、response并置为error(index.jsx#L145-L153);removed:用户删除列表项时,handleManualRemove先将status置为removed再移除(index.jsx#L170-L175)。
Demo 中正是利用info.file.status判断上传结果并给出message提示,这与组件的状态机完全对应。
另外,文件对象的匹配通过 getFileItem.js 实现:有uid时按 uid 匹配,否则按 name 匹配,这也是官方建议uid使用负数的原因——避免与 rc-upload 内部生成的 id 冲突。
三、从「点击上传」延伸的实战能力
基于 basic demo 的最小配置,配合其他官方 Demo 可以快速扩展出完整的上传能力:
3.1 上传前校验(beforeUpload)
参考 components/upload/demo/beforeUpload.md,在文件真正上传前拦截校验,例如只允许 JPG:
const props = { action: '/upload.do', beforeUpload(file) { const isJPG = file.type === 'image/jpeg'; if (!isJPG) { message.error('只能上传 JPG 文件哦!'); } return isJPG; // 返回 false 则停止上传 } };从源码看,beforeUpload的返回值会被记录为this.recentUploadStatus并返回给底层,从而决定是否继续上传流程(index.jsx#L155-L158);onStart中也会检查该状态决定是否接收新文件(index.jsx#L65)。
3.2 传入已上传的文件(defaultFileList / fileList)
- 使用
defaultFileList展示已上传的历史文件(见 components/upload/demo/defaultFileList.md),每项包含uid、name、status、url等字段; - 使用
fileList对列表进行完全受控管理(见 components/upload/demo/fileList.md),可在onChange中实现数量限制、读取服务端返回的远程路径并展示链接、按response.status筛选成功文件等自定义逻辑; - 展示下载链接时,只需在 fileList 数组项上设置
url属性,组件即会将其渲染为可点击的链接(见 uploadList.jsx)。
3.3 多文件与拖拽上传
- 设置
multiple: true支持按住 ctrl 多选(ie10+),见 components/upload/demo/multiple.md; - 使用
Upload.Dragger实现拖拽上传,见 components/upload/demo/drag.md。Dragger在源码中只是把type固定为'drag'的 Upload(index.jsx#L288-L292),渲染时监听onDrop、onDragOver、onDragLeave切换ant-upload-drag-hover等样式类。
四、使用前提与注意事项
action为必选参数,必须指向实际可接收上传文件的接口地址;Demo 中的/upload.do为占位地址;headers、multiple等能力依赖较新的浏览器特性(IE10+),老版本 IE 下需要额外的降级处理,官方文档在 components/upload/index.md 的「IE note」一节对此有专门说明;- 组件为自动上传模式:选中文件即触发上传,无需手动提交,这也是 basic demo「点击上传」体验的核心;
- 若需控制文件读取与预览,可参考 uploadList.jsx 中基于
FileReader.readAsDataURL的缩略图预览实现(适用于picture/picture-card列表样式)。
五、小结
components/upload/demo/basic.md以不足 40 行的代码完整演示了 ant-designUpload组件最核心的用法:通过action指定上传地址、以name定义字段名、用headers携带鉴权信息,并在onChange中依据file.status给出成功/失败反馈。结合 components/upload/index.md 的 API 文档与 components/upload/index.jsx 的源码实现,你可以快速上手并扩展出校验、多选、拖拽、受控列表等企业级上传场景。建议将此 Demo 作为起点,配合仓库内 demo 目录 的其余示例逐步深入。
【免费下载链接】ant-designAn enterprise-class UI design language and React UI library项目地址: https://gitcode.com/gh_mirrors/antde/ant-design
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考