antd上传组件(Upload)如何设计成受控组件

https://ant-design.antgroup.com/components/upload-cn

https://github.com/ant-design/ant-design/issues/2423

useAttachment.js:

import React from 'react'
import { Button, Upload, message } from 'antd'
import { v4 as uuidv4 } from 'uuid'
import {
  imageUrlFormat,
  uploadGetTokenFromLocalStorageForH5,
} from '../../../utils/tools'
import urls from '../../../api/urls'
import { Icon } from '../../../components/light'

export default function useAttachment({
  value = '',
  type = 'add',
  fileList,
  onChange,
  accept = '*.*',
  imgUrlCnd,
  videoDir = 'ai/file',
  filePrefix = '',
  handleChangeFile,
  maxCount = 2,
  pageType,
}) {
  const imageUrl = imageUrlFormat(imgUrlCnd)

  const uploadProps = {
    name: 'file',
    action: urls.light.uploadToCDN,
    data: (file) => {
      const uid = uuidv4()
      const reslutIndex = Array.from(file.name).findLastIndex(
        (item) => item === '.'
      )
      const fileName = uid + file.name.slice(reslutIndex, file.name.length)
      return {
        key: `${videoDir}/${
          filePrefix ? filePrefix + '-' : ''
        }${Date.now()}-${fileName}`,
        fname: fileName,
        token: uploadGetTokenFromLocalStorageForH5(),
      }
    },
    headers: {},
    maxCount,
    listType: 'picture',
    defaultFileList: [],
    fileList,
    accept,
    beforeUpload(file) {
      if (fileList.length >= maxCount) {
        message.warning(`最多只能上传${maxCount}个附件`)
        return false
      }
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
        onChange(undefined)
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`)
        handleChangeFile && handleChangeFile({ info })
        if (info.file?.response.code === 200) {
          onChange(info.file.response.data.key)
        }
      } else if (info.file.status === 'uploading') {
        handleChangeFile && handleChangeFile({ info })
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`)
      } else if (info.file.status === 'removed') {
        handleChangeFile && handleChangeFile({ info })

        onChange(info.file.response.data.key)
      }
    },
  }

  const getDom = () => {
    return (
      <>
        {pageType === '7' ? (
          <span>
            {type !== 'check' ? (
              <div className="m-ai-footer-attachment-wrap">
                <Upload {...uploadProps}>
                  <Button
                    icon={
                      <Icon
                        name="attachment2"
                        className="m-ai-footer-attachment-icon"
                      ></Icon>
                    }
                  />
                </Upload>
              </div>
            ) : value ? (
              <a href={imageUrl} target="_blank" rel="noreferrer">
                {imageUrl}
              </a>
            ) : null}
          </span>
        ) : null}
      </>
    )
  }

  return {
    attactmentGetDom: getDom,
  }
}
  import useAttachment from './useAttachment'
  


  const handleOnChangeForFile = (key) => {
    // console.log(key)
  }

  const handleChangeFile = ({ info }) => {
    console.log('fileList', info.fileList)
    if (Array.isArray(info.fileList)) {
      setFileList([...info.fileList])
    }

    if (info.file?.response?.data?.key) {
      if (info.file.status === 'done') {
        Api.h5
          .fileAdd({
            name: info.file.name,
            url: info.file.response.data.key,
            info: info.file,
          })
          .then((res) => {
            if (res.code === 200) {
              //antdMessage.success('成功')
            }
          })
      }
    }
  }

  const { attactmentGetDom } = useAttachment({
    ...props,
    pageType,
    fileList,
    onChange: handleOnChangeForFile,
    handleChangeFile,
  })

人工智能学习网站

https://chat.xutongbao.top

posted @ 2024-04-19 16:31  徐同保  阅读(29)  评论(0编辑  收藏  举报  来源