Upload上传

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

何时使用

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

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

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

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

代码演示

Upload 上传 - 图1

点击上传

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

  1. import { Upload, message, Button, Icon } from 'choerodon-ui';
  2. const props = {
  3. name: 'file',
  4. action: '//jsonplaceholder.typicode.com/posts/',
  5. headers: {
  6. authorization: 'authorization-text',
  7. },
  8. onChange(info) {
  9. if (info.file.status !== 'uploading') {
  10. console.log(info.file, info.fileList);
  11. }
  12. if (info.file.status === 'done') {
  13. message.success(`${info.file.name} file uploaded successfully`);
  14. } else if (info.file.status === 'error') {
  15. message.error(`${info.file.name} file upload failed.`);
  16. }
  17. },
  18. };
  19. ReactDOM.render(
  20. <Upload {...props}>
  21. <Button>
  22. <Icon type="file_upload" /> Click to Upload
  23. </Button>
  24. </Upload>,
  25. mountNode);

Upload 上传 - 图2

已上传的文件列表

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

  1. import { Upload, Button, Icon } from 'choerodon-ui';
  2. const props = {
  3. action: '//jsonplaceholder.typicode.com/posts/',
  4. onChange({ file, fileList }) {
  5. if (file.status !== 'uploading') {
  6. console.log(file, fileList);
  7. }
  8. },
  9. defaultFileList: [{
  10. uid: 1,
  11. name: 'xxx.png',
  12. status: 'done',
  13. reponse: 'Server Error 500', // custom error message to show
  14. url: 'http://www.baidu.com/xxx.png',
  15. }, {
  16. uid: 2,
  17. name: 'yyy.png',
  18. status: 'done',
  19. url: 'http://www.baidu.com/yyy.png',
  20. }, {
  21. uid: 3,
  22. name: 'zzz.png',
  23. status: 'error',
  24. reponse: 'Server Error 500', // custom error message to show
  25. url: 'http://www.baidu.com/zzz.png',
  26. }],
  27. };
  28. ReactDOM.render(
  29. <Upload {...props}>
  30. <Button>
  31. <Icon type="file_upload" /> Upload
  32. </Button>
  33. </Upload>,
  34. mountNode);

Upload 上传 - 图3

完全控制的上传列表

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

1) 上传列表数量的限制。

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

3) 按照服务器返回信息筛选成功上传的文件。

  1. import { Upload, Button, Icon } from 'choerodon-ui';
  2. class MyUpload extends React.Component {
  3. state = {
  4. fileList: [{
  5. uid: -1,
  6. name: 'xxx.png',
  7. status: 'done',
  8. url: 'http://www.baidu.com/xxx.png',
  9. }],
  10. }
  11. handleChange = (info) => {
  12. let fileList = info.fileList;
  13. // 1. Limit the number of uploaded files
  14. // Only to show two recent uploaded files, and old ones will be replaced by the new
  15. fileList = fileList.slice(-2);
  16. // 2. read from response and show file link
  17. fileList = fileList.map((file) => {
  18. if (file.response) {
  19. // Component will show file.url as link
  20. file.url = file.response.url;
  21. }
  22. return file;
  23. });
  24. // 3. filter successfully uploaded files according to response from server
  25. fileList = fileList.filter((file) => {
  26. if (file.response) {
  27. return file.response.status === 'success';
  28. }
  29. return true;
  30. });
  31. this.setState({ fileList });
  32. }
  33. render() {
  34. const props = {
  35. action: '//jsonplaceholder.typicode.com/posts/',
  36. onChange: this.handleChange,
  37. multiple: true,
  38. };
  39. return (
  40. <Upload {...props} fileList={this.state.fileList}>
  41. <Button>
  42. <Icon type="file_upload" /> upload
  43. </Button>
  44. </Upload>
  45. );
  46. }
  47. }
  48. ReactDOM.render(<MyUpload />, mountNode);

Upload 上传 - 图4

图片列表样式

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

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

Upload 上传 - 图5

用户头像

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

beforeUpload 的返回值可以是一个 Promise 以支持也支持异步检查:示例

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

Upload 上传 - 图6

照片墙

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

  1. import { Upload, Icon, Modal } from 'choerodon-ui';
  2. class PicturesWall extends React.Component {
  3. state = {
  4. previewVisible: false,
  5. previewImage: '',
  6. fileList: [{
  7. uid: -1,
  8. name: 'xxx.png',
  9. status: 'done',
  10. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  11. }],
  12. };
  13. handleCancel = () => this.setState({ previewVisible: false })
  14. handlePreview = (file) => {
  15. this.setState({
  16. previewImage: file.url || file.thumbUrl,
  17. previewVisible: true,
  18. });
  19. }
  20. handleChange = ({ fileList }) => this.setState({ fileList })
  21. render() {
  22. const { previewVisible, previewImage, fileList } = this.state;
  23. const uploadButton = (
  24. <div>
  25. <Icon type="add" />
  26. <div className="c7n-upload-text">Upload</div>
  27. </div>
  28. );
  29. return (
  30. <div className="clearfix">
  31. <Upload
  32. action="//jsonplaceholder.typicode.com/posts/"
  33. listType="picture-card"
  34. fileList={fileList}
  35. onPreview={this.handlePreview}
  36. onChange={this.handleChange}
  37. >
  38. {fileList.length >= 3 ? null : uploadButton}
  39. </Upload>
  40. <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
  41. <img alt="example" style={{ width: '100%' }} src={previewImage} />
  42. </Modal>
  43. </div>
  44. );
  45. }
  46. }
  47. ReactDOM.render(<PicturesWall />, mountNode);
  1. /* you can make up upload button and sample style by using stylesheets */
  2. .c7n-upload-select-picture-card i {
  3. font-size: 32px;
  4. color: #999;
  5. }
  6. .c7n-upload-select-picture-card .c7n-upload-text {
  7. margin-top: 8px;
  8. color: #666;
  9. }

Upload 上传 - 图7

拖拽上传

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

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

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

Upload 上传 - 图8

手动上传

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

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

API

服务端上传接口实现可以参考 jQuery-File-Upload

参数说明类型默认值
accept接受上传的文件类型, 详见 input accept Attributestring
action必选参数, 上传的地址string
beforeUpload上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。支持返回一个 Promise 对象,Promise 对象 reject 时则停止上传,resolve 时开始上传。注意:IE9 不支持该方法(file, fileList) => boolean | Promise
customRequest通过覆盖默认的上传行为,可以自定义自己的上传实现Function
data上传所需参数或返回上传参数的方法object|function(file)
defaultFileList默认已经上传的文件列表object[]
disabled是否禁用booleanfalse
fileList已经上传的文件列表(受控)object[]
headers设置上传的请求头部,IE10 以上有效object
listType上传列表的内建样式,支持三种基本样式 text, picturepicture-cardstring'text'
multiple是否支持多选文件,ie10+ 支持。开启后按住 ctrl 可选择多个文件。booleanfalse
name发到后台的文件参数名string'file'
showUploadList是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon 和 showRemoveIconBoolean or { showPreviewIcon?: boolean, showRemoveIcon?: boolean }true
supportServerRender服务端渲染时需要打开这个booleanfalse
withCredentials上传请求时是否携带 cookiebooleanfalse
onChange上传文件改变时的状态,详见 onChangeFunction
onPreview点击文件链接或预览图标时的回调Function(file)
onRemove 点击移除文件时的回调,返回值为 false 时不移除。支持返回一个 Promise 对象,Promise 对象 resolve(false) 或 reject 时不移除。 Function(file): boolean | Promise
onSuccess 上传成功事件 Function(response, file)
onProgress 上传进度中事件 Function({ percent }, file)
onError 上传失败事件 Function(error, response, file)

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 上传中的服务端响应内容,包含了上传进度等信息,高级浏览器支持。

显示下载链接

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

customRequest

IE note