Upload上传

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

何时使用

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

  • 当需要上传一个或一些文件时。

  • 当需要展现上传的进度时。

  • 当需要使用拖拽交互时。

代码演示

Upload上传 - 图1

点击上传

经典款式,用户点击按钮弹出文件选择框。

  1. import { Upload, message, Button } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. const props = {
  4. name: 'file',
  5. action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  6. headers: {
  7. authorization: 'authorization-text',
  8. },
  9. onChange(info) {
  10. if (info.file.status !== 'uploading') {
  11. console.log(info.file, info.fileList);
  12. }
  13. if (info.file.status === 'done') {
  14. message.success(`${info.file.name} file uploaded successfully`);
  15. } else if (info.file.status === 'error') {
  16. message.error(`${info.file.name} file upload failed.`);
  17. }
  18. },
  19. };
  20. ReactDOM.render(
  21. <Upload {...props}>
  22. <Button>
  23. <UploadOutlined /> Click to Upload
  24. </Button>
  25. </Upload>,
  26. mountNode,
  27. );

Upload上传 - 图2

已上传的文件列表

使用 defaultFileList 设置已上传的内容。

  1. import { Upload, Button } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. const props = {
  4. action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  5. onChange({ file, fileList }) {
  6. if (file.status !== 'uploading') {
  7. console.log(file, fileList);
  8. }
  9. },
  10. defaultFileList: [
  11. {
  12. uid: '1',
  13. name: 'xxx.png',
  14. status: 'done',
  15. response: 'Server Error 500', // custom error message to show
  16. url: 'http://www.baidu.com/xxx.png',
  17. },
  18. {
  19. uid: '2',
  20. name: 'yyy.png',
  21. status: 'done',
  22. url: 'http://www.baidu.com/yyy.png',
  23. },
  24. {
  25. uid: '3',
  26. name: 'zzz.png',
  27. status: 'error',
  28. response: 'Server Error 500', // custom error message to show
  29. url: 'http://www.baidu.com/zzz.png',
  30. },
  31. ],
  32. };
  33. ReactDOM.render(
  34. <Upload {...props}>
  35. <Button>
  36. <UploadOutlined /> Upload
  37. </Button>
  38. </Upload>,
  39. mountNode,
  40. );

Upload上传 - 图3

完全控制的上传列表

使用 fileList 对列表进行完全控制,可以实现各种自定义功能,以下演示二种情况:

  • 上传列表数量的限制。

  • 读取远程路径并显示链接。

  1. import { Upload, Button } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. class MyUpload extends React.Component {
  4. state = {
  5. fileList: [
  6. {
  7. uid: '-1',
  8. name: 'xxx.png',
  9. status: 'done',
  10. url: 'http://www.baidu.com/xxx.png',
  11. },
  12. ],
  13. };
  14. handleChange = info => {
  15. let fileList = [...info.fileList];
  16. // 1. Limit the number of uploaded files
  17. // Only to show two recent uploaded files, and old ones will be replaced by the new
  18. fileList = fileList.slice(-2);
  19. // 2. Read from response and show file link
  20. fileList = fileList.map(file => {
  21. if (file.response) {
  22. // Component will show file.url as link
  23. file.url = file.response.url;
  24. }
  25. return file;
  26. });
  27. this.setState({ fileList });
  28. };
  29. render() {
  30. const props = {
  31. action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  32. onChange: this.handleChange,
  33. multiple: true,
  34. };
  35. return (
  36. <Upload {...props} fileList={this.state.fileList}>
  37. <Button>
  38. <UploadOutlined /> Upload
  39. </Button>
  40. </Upload>
  41. );
  42. }
  43. }
  44. ReactDOM.render(<MyUpload />, mountNode);

Upload上传 - 图4

文件夹上传

支持上传一个文件夹里的所有文件。

  1. import { Upload, Button } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. ReactDOM.render(
  4. <Upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" directory>
  5. <Button>
  6. <UploadOutlined /> Upload Directory
  7. </Button>
  8. </Upload>,
  9. mountNode,
  10. );

Upload上传 - 图5

图片列表样式

上传文件为图片,可展示本地缩略图。IE8/9 不支持浏览器本地缩略图展示(Ref),可以写 thumbUrl 属性来代替。

  1. import { Upload, Button } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. const fileList = [
  4. {
  5. uid: '-1',
  6. name: 'xxx.png',
  7. status: 'done',
  8. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  9. thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  10. },
  11. {
  12. uid: '-2',
  13. name: 'yyy.png',
  14. status: 'error',
  15. },
  16. ];
  17. const props = {
  18. action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  19. listType: 'picture',
  20. defaultFileList: [...fileList],
  21. };
  22. const props2 = {
  23. action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  24. listType: 'picture',
  25. defaultFileList: [...fileList],
  26. className: 'upload-list-inline',
  27. };
  28. ReactDOM.render(
  29. <div>
  30. <Upload {...props}>
  31. <Button>
  32. <UploadOutlined /> Upload
  33. </Button>
  34. </Upload>
  35. <br />
  36. <br />
  37. <Upload {...props2}>
  38. <Button>
  39. <UploadOutlined /> Upload
  40. </Button>
  41. </Upload>
  42. </div>,
  43. mountNode,
  44. );
  1. /* tile uploaded pictures */
  2. .upload-list-inline .ant-upload-list-item {
  3. float: left;
  4. width: 200px;
  5. margin-right: 8px;
  6. }
  7. .upload-list-inline [class*='-upload-list-rtl'] .ant-upload-list-item {
  8. float: right;
  9. }
  10. .upload-list-inline .ant-upload-animate-enter {
  11. animation-name: uploadAnimateInlineIn;
  12. }
  13. .upload-list-inline .ant-upload-animate-leave {
  14. animation-name: uploadAnimateInlineOut;
  15. }

Upload上传 - 图6

上传前转换文件

使用 transformFile 转换上传的文件(例如添加水印)。

  1. import { Upload, Button } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. const props = {
  4. action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  5. transformFile(file) {
  6. return new Promise(resolve => {
  7. const reader = new FileReader();
  8. reader.readAsDataURL(file);
  9. reader.onload = () => {
  10. const canvas = document.createElement('canvas');
  11. const img = document.createElement('img');
  12. img.src = reader.result;
  13. img.onload = () => {
  14. const ctx = canvas.getContext('2d');
  15. ctx.drawImage(img, 0, 0);
  16. ctx.fillStyle = 'red';
  17. ctx.textBaseline = 'middle';
  18. ctx.fillText('Ant Design', 20, 20);
  19. canvas.toBlob(resolve);
  20. };
  21. };
  22. });
  23. },
  24. };
  25. ReactDOM.render(
  26. <div>
  27. <Upload {...props}>
  28. <Button>
  29. <UploadOutlined /> Upload
  30. </Button>
  31. </Upload>
  32. </div>,
  33. mountNode,
  34. );

Upload上传 - 图7

自定义交互图标

使用 showUploadList 设置列表交互图标。

  1. import { Upload, Button } from 'antd';
  2. import { UploadOutlined, StarOutlined } from '@ant-design/icons';
  3. const props = {
  4. action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  5. onChange({ file, fileList }) {
  6. if (file.status !== 'uploading') {
  7. console.log(file, fileList);
  8. }
  9. },
  10. defaultFileList: [
  11. {
  12. uid: '1',
  13. name: 'xxx.png',
  14. status: 'done',
  15. response: 'Server Error 500', // custom error message to show
  16. url: 'http://www.baidu.com/xxx.png',
  17. },
  18. {
  19. uid: '2',
  20. name: 'yyy.png',
  21. status: 'done',
  22. url: 'http://www.baidu.com/yyy.png',
  23. },
  24. {
  25. uid: '3',
  26. name: 'zzz.png',
  27. status: 'error',
  28. response: 'Server Error 500', // custom error message to show
  29. url: 'http://www.baidu.com/zzz.png',
  30. },
  31. ],
  32. showUploadList: {
  33. showDownloadIcon: true,
  34. downloadIcon: 'download ',
  35. showRemoveIcon: true,
  36. removeIcon: <StarOutlined onClick={e => console.log(e, 'custom removeIcon event')} />,
  37. },
  38. };
  39. ReactDOM.render(
  40. <Upload {...props}>
  41. <Button>
  42. <UploadOutlined /> Upload
  43. </Button>
  44. </Upload>,
  45. mountNode,
  46. );

Upload上传 - 图8

用户头像

点击上传用户头像,并使用 beforeUpload 限制用户上传的图片格式和大小。

beforeUpload 的返回值可以是一个 Promise 以支持异步处理,如服务端校验等:示例

  1. import { Upload, message } from 'antd';
  2. import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
  3. function getBase64(img, callback) {
  4. const reader = new FileReader();
  5. reader.addEventListener('load', () => callback(reader.result));
  6. reader.readAsDataURL(img);
  7. }
  8. function beforeUpload(file) {
  9. const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  10. if (!isJpgOrPng) {
  11. message.error('You can only upload JPG/PNG file!');
  12. }
  13. const isLt2M = file.size / 1024 / 1024 < 2;
  14. if (!isLt2M) {
  15. message.error('Image must smaller than 2MB!');
  16. }
  17. return isJpgOrPng && isLt2M;
  18. }
  19. class Avatar extends React.Component {
  20. state = {
  21. loading: false,
  22. };
  23. handleChange = info => {
  24. if (info.file.status === 'uploading') {
  25. this.setState({ loading: true });
  26. return;
  27. }
  28. if (info.file.status === 'done') {
  29. // Get this url from response in real world.
  30. getBase64(info.file.originFileObj, imageUrl =>
  31. this.setState({
  32. imageUrl,
  33. loading: false,
  34. }),
  35. );
  36. }
  37. };
  38. render() {
  39. const uploadButton = (
  40. <div>
  41. {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
  42. <div className="ant-upload-text">Upload</div>
  43. </div>
  44. );
  45. const { imageUrl } = this.state;
  46. return (
  47. <Upload
  48. name="avatar"
  49. listType="picture-card"
  50. className="avatar-uploader"
  51. showUploadList={false}
  52. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  53. beforeUpload={beforeUpload}
  54. onChange={this.handleChange}
  55. >
  56. {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
  57. </Upload>
  58. );
  59. }
  60. }
  61. ReactDOM.render(<Avatar />, mountNode);
  1. .avatar-uploader > .ant-upload {
  2. width: 128px;
  3. height: 128px;
  4. }

Upload上传 - 图9

照片墙

用户可以上传图片并在列表中显示缩略图。当上传照片数到达限制后,上传按钮消失。

  1. import { Upload, Modal } from 'antd';
  2. import { PlusOutlined } from '@ant-design/icons';
  3. function getBase64(file) {
  4. return new Promise((resolve, reject) => {
  5. const reader = new FileReader();
  6. reader.readAsDataURL(file);
  7. reader.onload = () => resolve(reader.result);
  8. reader.onerror = error => reject(error);
  9. });
  10. }
  11. class PicturesWall extends React.Component {
  12. state = {
  13. previewVisible: false,
  14. previewImage: '',
  15. fileList: [
  16. {
  17. uid: '-1',
  18. name: 'image.png',
  19. status: 'done',
  20. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  21. },
  22. {
  23. uid: '-2',
  24. name: 'image.png',
  25. status: 'done',
  26. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  27. },
  28. {
  29. uid: '-3',
  30. name: 'image.png',
  31. status: 'done',
  32. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  33. },
  34. {
  35. uid: '-4',
  36. name: 'image.png',
  37. status: 'done',
  38. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  39. },
  40. {
  41. uid: '-5',
  42. name: 'image.png',
  43. status: 'error',
  44. },
  45. ],
  46. };
  47. handleCancel = () => this.setState({ previewVisible: false });
  48. handlePreview = async file => {
  49. if (!file.url && !file.preview) {
  50. file.preview = await getBase64(file.originFileObj);
  51. }
  52. this.setState({
  53. previewImage: file.url || file.preview,
  54. previewVisible: true,
  55. });
  56. };
  57. handleChange = ({ fileList }) => this.setState({ fileList });
  58. render() {
  59. const { previewVisible, previewImage, fileList } = this.state;
  60. const uploadButton = (
  61. <div>
  62. <PlusOutlined />
  63. <div className="ant-upload-text">Upload</div>
  64. </div>
  65. );
  66. return (
  67. <div className="clearfix">
  68. <Upload
  69. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  70. listType="picture-card"
  71. fileList={fileList}
  72. onPreview={this.handlePreview}
  73. onChange={this.handleChange}
  74. >
  75. {fileList.length >= 8 ? null : uploadButton}
  76. </Upload>
  77. <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
  78. <img alt="example" style={{ width: '100%' }} src={previewImage} />
  79. </Modal>
  80. </div>
  81. );
  82. }
  83. }
  84. ReactDOM.render(<PicturesWall />, mountNode);
  1. /* you can make up upload button and sample style by using stylesheets */
  2. .ant-upload-select-picture-card i {
  3. color: #999;
  4. font-size: 32px;
  5. }
  6. .ant-upload-select-picture-card .ant-upload-text {
  7. margin-top: 8px;
  8. color: #666;
  9. }

Upload上传 - 图10

拖拽上传

把文件拖入指定区域,完成上传,同样支持点击上传。

设置 multiple 后,在 IE10+ 可以一次上传多个文件。

  1. import { Upload, message } from 'antd';
  2. import { InboxOutlined } from '@ant-design/icons';
  3. const { Dragger } = Upload;
  4. const props = {
  5. name: 'file',
  6. multiple: true,
  7. action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  8. onChange(info) {
  9. const { status } = info.file;
  10. if (status !== 'uploading') {
  11. console.log(info.file, info.fileList);
  12. }
  13. if (status === 'done') {
  14. message.success(`${info.file.name} file uploaded successfully.`);
  15. } else if (status === 'error') {
  16. message.error(`${info.file.name} file upload failed.`);
  17. }
  18. },
  19. };
  20. ReactDOM.render(
  21. <Dragger {...props}>
  22. <p className="ant-upload-drag-icon">
  23. <InboxOutlined />
  24. </p>
  25. <p className="ant-upload-text">Click or drag file to this area to upload</p>
  26. <p className="ant-upload-hint">
  27. Support for a single or bulk upload. Strictly prohibit from uploading company data or other
  28. band files
  29. </p>
  30. </Dragger>,
  31. mountNode,
  32. );

Upload上传 - 图11

手动上传

beforeUpload 返回 false 后,手动上传文件。

  1. import { Upload, Button, message } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. import reqwest from 'reqwest';
  4. class Demo extends React.Component {
  5. state = {
  6. fileList: [],
  7. uploading: false,
  8. };
  9. handleUpload = () => {
  10. const { fileList } = this.state;
  11. const formData = new FormData();
  12. fileList.forEach(file => {
  13. formData.append('files[]', file);
  14. });
  15. this.setState({
  16. uploading: true,
  17. });
  18. // You can use any AJAX library you like
  19. reqwest({
  20. url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  21. method: 'post',
  22. processData: false,
  23. data: formData,
  24. success: () => {
  25. this.setState({
  26. fileList: [],
  27. uploading: false,
  28. });
  29. message.success('upload successfully.');
  30. },
  31. error: () => {
  32. this.setState({
  33. uploading: false,
  34. });
  35. message.error('upload failed.');
  36. },
  37. });
  38. };
  39. render() {
  40. const { uploading, fileList } = this.state;
  41. const props = {
  42. onRemove: file => {
  43. this.setState(state => {
  44. const index = state.fileList.indexOf(file);
  45. const newFileList = state.fileList.slice();
  46. newFileList.splice(index, 1);
  47. return {
  48. fileList: newFileList,
  49. };
  50. });
  51. },
  52. beforeUpload: file => {
  53. this.setState(state => ({
  54. fileList: [...state.fileList, file],
  55. }));
  56. return false;
  57. },
  58. fileList,
  59. };
  60. return (
  61. <div>
  62. <Upload {...props}>
  63. <Button>
  64. <UploadOutlined /> Select File
  65. </Button>
  66. </Upload>
  67. <Button
  68. type="primary"
  69. onClick={this.handleUpload}
  70. disabled={fileList.length === 0}
  71. loading={uploading}
  72. style={{ marginTop: 16 }}
  73. >
  74. {uploading ? 'Uploading' : 'Start Upload'}
  75. </Button>
  76. </div>
  77. );
  78. }
  79. }
  80. ReactDOM.render(<Demo />, mountNode);

Upload上传 - 图12

自定义预览

自定义本地预览,用于处理非图片格式文件(例如视频文件)。

  1. import { Upload, Button } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. const props = {
  4. action: '//jsonplaceholder.typicode.com/posts/',
  5. listType: 'picture',
  6. previewFile(file) {
  7. console.log('Your upload file:', file);
  8. // Your process logic. Here we just mock to the same file
  9. return fetch('https://next.json-generator.com/api/json/get/4ytyBoLK8', {
  10. method: 'POST',
  11. body: file,
  12. })
  13. .then(res => res.json())
  14. .then(({ thumbnail }) => thumbnail);
  15. },
  16. };
  17. ReactDOM.render(
  18. <div>
  19. <Upload {...props}>
  20. <Button>
  21. <UploadOutlined /> Upload
  22. </Button>
  23. </Upload>
  24. </div>,
  25. mountNode,
  26. );

Upload上传 - 图13

阿里云 OSS

使用阿里云 OSS 上传示例.

  1. import { Form, Upload, message, Button } from 'antd';
  2. import { UploadOutlined } from '@ant-design/icons';
  3. class AliyunOSSUpload extends React.Component {
  4. state = {
  5. OSSData: {},
  6. };
  7. async componentDidMount() {
  8. await this.init();
  9. }
  10. init = async () => {
  11. try {
  12. const OSSData = await this.mockGetOSSData();
  13. this.setState({
  14. OSSData,
  15. });
  16. } catch (error) {
  17. message.error(error);
  18. }
  19. };
  20. // Mock get OSS api
  21. // https://help.aliyun.com/document_detail/31988.html
  22. mockGetOSSData = () => {
  23. return {
  24. dir: 'user-dir/',
  25. expire: '1577811661',
  26. host: '//www.mocky.io/v2/5cc8019d300000980a055e76',
  27. accessId: 'c2hhb2RhaG9uZw==',
  28. policy: 'eGl4aWhhaGFrdWt1ZGFkYQ==',
  29. signature: 'ZGFob25nc2hhbw==',
  30. };
  31. };
  32. onChange = ({ fileList }) => {
  33. const { onChange } = this.props;
  34. console.log('Aliyun OSS:', fileList);
  35. if (onChange) {
  36. onChange([...fileList]);
  37. }
  38. };
  39. onRemove = file => {
  40. const { value, onChange } = this.props;
  41. const files = value.filter(v => v.url !== file.url);
  42. if (onChange) {
  43. onChange(files);
  44. }
  45. };
  46. transformFile = file => {
  47. const { OSSData } = this.state;
  48. const suffix = file.name.slice(file.name.lastIndexOf('.'));
  49. const filename = Date.now() + suffix;
  50. file.url = OSSData.dir + filename;
  51. return file;
  52. };
  53. getExtraData = file => {
  54. const { OSSData } = this.state;
  55. return {
  56. key: file.url,
  57. OSSAccessKeyId: OSSData.accessId,
  58. policy: OSSData.policy,
  59. Signature: OSSData.signature,
  60. };
  61. };
  62. beforeUpload = async () => {
  63. const { OSSData } = this.state;
  64. const expire = OSSData.expire * 1000;
  65. if (expire < Date.now()) {
  66. await this.init();
  67. }
  68. return true;
  69. };
  70. render() {
  71. const { value } = this.props;
  72. const props = {
  73. name: 'file',
  74. fileList: value,
  75. action: this.state.OSSData.host,
  76. onChange: this.onChange,
  77. onRemove: this.onRemove,
  78. transformFile: this.transformFile,
  79. data: this.getExtraData,
  80. beforeUpload: this.beforeUpload,
  81. };
  82. return (
  83. <Upload {...props}>
  84. <Button>
  85. <UploadOutlined /> Click to Upload
  86. </Button>
  87. </Upload>
  88. );
  89. }
  90. }
  91. const FormPage = () => (
  92. <Form labelCol={{ span: 4 }}>
  93. <Form.Item label="Photos" name="photos">
  94. <AliyunOSSUpload />
  95. </Form.Item>
  96. </Form>
  97. );
  98. ReactDOM.render(<FormPage />, mountNode);

API

参数说明类型默认值版本
accept接受上传的文件类型, 详见 input accept Attributestring
action上传的地址string|(file) => Promise
method上传请求的 http methodstring'post'
directory支持上传文件夹(caniusebooleanfalse
beforeUpload上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。支持返回一个 Promise 对象,Promise 对象 reject 时则停止上传,resolve 时开始上传( resolve 传入 FileBlob 对象则上传 resolve 传入对象)。注意:IE9 不支持该方法(file, fileList) => boolean | Promise
customRequest通过覆盖默认的上传行为,可以自定义自己的上传实现Function
data上传所需额外参数或返回上传额外参数的方法object|(file) => object
defaultFileList默认已经上传的文件列表object[]
disabled是否禁用booleanfalse
fileList已经上传的文件列表(受控),使用此参数时,如果遇到 onChange 只调用一次的问题,请参考 #2423object[]
headers设置上传的请求头部,IE10 以上有效object
listType上传列表的内建样式,支持三种基本样式 text, picturepicture-cardstring'text'
multiple是否支持多选文件,ie10+ 支持。开启后按住 ctrl 可选择多个文件booleanfalse
name发到后台的文件参数名string'file'
previewFile自定义文件预览逻辑(file: File | Blob) => Promise<dataURL: string>
showUploadList是否展示文件列表, 可设为一个对象,用于单独设定 showPreviewIcon, showRemoveIcon, showDownloadIcon, removeIcondownloadIconBoolean or { showPreviewIcon?: boolean, showRemoveIcon?: boolean, showDownloadIcon?: boolean, removeIcon?: React.ReactNode, downloadIcon?: React.ReactNode }true
supportServerRender服务端渲染时需要打开这个booleanfalse
withCredentials上传请求时是否携带 cookiebooleanfalse
openFileDialogOnClick点击打开文件对话框booleantrue
onChange上传文件改变时的状态,详见 onChangeFunction
onPreview点击文件链接或预览图标时的回调Function(file)
onRemove 点击移除文件时的回调,返回值为 false 时不移除。支持返回一个 Promise 对象,Promise 对象 resolve(false) 或 reject 时不移除。 Function(file): boolean | Promise
onDownload点击下载文件时的回调,如果没有指定,则默认跳转到文件 url 对应的标签页。Function(file): void跳转新标签页
transformFile 在上传之前转换文件。支持返回一个 Promise 对象 Function(file): string | Blob | File | Promise<string | Blob | File>
iconRender自定义显示 icon(file: UploadFile, listType?: UploadListType) => React.ReactNode

onChange

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

文件状态改变的回调,返回为:

  1. {
  2. file: { /* ... */ },
  3. fileList: [ /* ... */ ],
  4. event: { /* ... */ },
  5. }
  • file 当前操作的文件对象。
  1. {
  2. uid: 'uid', // 文件唯一标识,建议设置为负数,防止和内部产生的 id 冲突
  3. name: 'xx.png' // 文件名
  4. status: 'done', // 状态有:uploading done error removed
  5. response: '{"status": "success"}', // 服务端响应内容
  6. linkProps: '{"download": "image"}', // 下载链接额外的 HTML 属性
  7. }
  • fileList 当前的文件列表。

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

FAQ

服务端如何实现?

如何显示下载链接?

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

customRequest 怎么使用?

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