123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- import React, { useState, useEffect } from 'react'
- import { Upload, Button, Icon } from 'antd';
- import { uploaderProps } from '../../utils/upload';
-
- /**
- * value 数据的接收格式 [{ url: xxxxx.mp4 }]
- * size 参数限制可以上传多少个文件
- * @param { value, size } props
- */
- function fileUpload(props) {
-
- const { value } = props
- // console.log('fileUploadProps: ', props)
- // eslint-disable-next-line react-hooks/rules-of-hooks
- const [defaultFileList, setDefaultFileList] = useState([])
-
- // eslint-disable-next-line react-hooks/rules-of-hooks
- useEffect(() => {
- setDefaultValue()
- }, [props.value]);
-
-
- function getFileList() {
- console.log('fileUpload: ', value)
- // value 数据的接收格式 [{ url: xxxxx.mp4 }, { url: xxxxx.jpg }]
- return (value || []).filter(f => f !== undefined).map((img, inx) => ({ uid: inx, url: img, name: img.substring(img.lastIndexOf('/') + 1, img.length), status: 'done' }))
- }
-
- function setDefaultValue() {
- if (!value) {
- return;
- }
-
- setDefaultFileList(getFileList())
- }
-
- function onFileChange({ file, fileList }) {
- console.log(file, fileList)
- setDefaultFileList(fileList)
- if (file.status === 'uploading') {
- return
- }
-
- if (file.status === 'done' || file.status === 'removed') {
-
- // 因为这个控件本身返回的数据格式 [{ ..., response: '服务器返回的数据' }]
- // 但是 我这里自己用的时候 传入的数据是 [ 'xxxx.mp4', 'xxxx.jpg' ], 然后通过 getFileList() 转换成了 [{ url: 'xxx.mp4' }] 这样的格式
-
- // 原因是因为 控件返回的数据 和 fileList 展示已经上传的数据 的格式字段不一样
-
- const resFileList = fileList.filter(f => f.response !== undefined).map(i => i.response)
- const tempFileList = fileList.filter(f => f.url !== undefined).map(i => i.url)
- const resultList = tempFileList.concat(resFileList || [])
- props.onChange(resultList)
- }
- }
-
- return (
- <>
- <Upload
- { ...uploaderProps }
- {...props}
- onChange={onFileChange}
- fileList={defaultFileList}
- >
- {
- props.size ?
- (props.size > defaultFileList.length
- && (
- <Button>
- <Icon type="upload" /> {props.label}
- </Button>
- )) : (
- <Button>
- <Icon type="upload" /> {props.label}
- </Button>
- )
- }
- </Upload>
- </>
- )
- }
-
- export default fileUpload
|