FileUpload.jsx 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import React, { useState, useEffect } from 'react'
  2. import { Upload, Button, Icon } from 'antd';
  3. import { uploaderProps } from '../../utils/upload';
  4. /**
  5. * value 数据的接收格式 [{ url: xxxxx.mp4 }]
  6. * size 参数限制可以上传多少个文件
  7. * @param { value, size } props
  8. */
  9. function fileUpload(props) {
  10. const { value } = props
  11. // console.log('fileUploadProps: ', props)
  12. // eslint-disable-next-line react-hooks/rules-of-hooks
  13. const [defaultFileList, setDefaultFileList] = useState([])
  14. // eslint-disable-next-line react-hooks/rules-of-hooks
  15. useEffect(() => {
  16. setDefaultValue()
  17. }, [props.value]);
  18. function getFileList() {
  19. console.log('fileUpload: ', value)
  20. // value 数据的接收格式 [{ url: xxxxx.mp4 }, { url: xxxxx.jpg }]
  21. return (value || []).filter(f => f !== undefined).map((img, inx) => ({ uid: inx, url: img, name: img.substring(img.lastIndexOf('/') + 1, img.length), status: 'done' }))
  22. }
  23. function setDefaultValue() {
  24. if (!value) {
  25. return;
  26. }
  27. setDefaultFileList(getFileList())
  28. }
  29. function onFileChange({ file, fileList }) {
  30. console.log(file, fileList)
  31. setDefaultFileList(fileList)
  32. if (file.status === 'uploading') {
  33. return
  34. }
  35. if (file.status === 'done' || file.status === 'removed') {
  36. // 因为这个控件本身返回的数据格式 [{ ..., response: '服务器返回的数据' }]
  37. // 但是 我这里自己用的时候 传入的数据是 [ 'xxxx.mp4', 'xxxx.jpg' ], 然后通过 getFileList() 转换成了 [{ url: 'xxx.mp4' }] 这样的格式
  38. // 原因是因为 控件返回的数据 和 fileList 展示已经上传的数据 的格式字段不一样
  39. const resFileList = fileList.filter(f => f.response !== undefined).map(i => i.response)
  40. const tempFileList = fileList.filter(f => f.url !== undefined).map(i => i.url)
  41. const resultList = tempFileList.concat(resFileList || [])
  42. props.onChange(resultList)
  43. }
  44. }
  45. return (
  46. <>
  47. <Upload
  48. { ...uploaderProps }
  49. {...props}
  50. onChange={onFileChange}
  51. fileList={defaultFileList}
  52. >
  53. {
  54. props.size ?
  55. (props.size > defaultFileList.length
  56. && (
  57. <Button>
  58. <Icon type="upload" /> {props.label}
  59. </Button>
  60. )) : (
  61. <Button>
  62. <Icon type="upload" /> {props.label}
  63. </Button>
  64. )
  65. }
  66. </Upload>
  67. </>
  68. )
  69. }
  70. export default fileUpload