• 封装react upload上传组件,允许Form与upload联动(组件独立已解耦)


    原有问题

    表单填写往往有某个表单项是文件上传,但是我们不得不在异步上传完毕之后拿着响应体给formData的某个属性塞文件路径,但是如果表单中存在若干个上传路径需要赛给不同的表单属性,这时候怎么办?难不成需要定义多个上传方法?

    效果

    在这里插入图片描述
    在这里插入图片描述
    支持大图查看删除操作,拿装泥照片举例,表单绑定的属性是moveImgA存的时图片所在服务器上的路径,那么首先在数据回显时,该字段有值则会自动回显,其次在完成上传后会自动填充表单的moveImgA属性为该图片的保存路径,最后点击删除图片操作,会自动将表单中的moveImgA属性置空

    代码

    js

    import React, { useEffect, useState, useRef } from 'react';
    import { Upload, message, Button, Image, Space } from 'antd';
    import { useModel } from 'umi';
    import { PlusOutlined, UploadOutlined, CloseOutlined } from '@ant-design/icons'
    import ImgCrop from 'antd-img-crop';
    import { SortableContainer, SortableElement, arrayMove } from 'react-sortable-hoc';
    import styles from './index.less';
    import md5 from 'md5';
    
    const GlobalUploadOss = ({
      maxCount = 1,
      onChange,
      onRemove,
      title,
      accept = 'image/*',
      value,
      crop,
      data: { type = 'default' },
      listType = 'picture-card',
      supportSort,
      ...props
    }) => {
      const { initialState: { uploadAction, ossSuffix } } = useModel('@@initialState');
      
      const [previewSrc, setPreviewSrc] = useState()
      // const [ossSTSInfo, setOssSTSInfo] = useState();
      const [fileList, setFileList] = useState(() => {
        if (accept === '.apk') { //上传apk专用
          return []
        } else {
          return value?.split(',').map((item, index) => ({
            uid: 'img' + index,
            // name: item.split('/').at(-1), //google兼容,safari等其他浏览器不兼容
            name: item.split('/').slice(-1)?.[0],
            status: 'done',
            url: item,
            thumbUrl: accept.indexOf('video') != -1 ? item + ossSuffix : item
          })) || []
        }
      })
      // useEffect(async () => {
      //   const res = await getOSSData()
      //   setOssSTSInfo(res)
      // }, [])
    
      const beforeUpload = async (file, fileList) => {
        //上传前文件重命名
        // file.ossName = accept == '.apk' ? 'Android/' + type : `${type}/${randomString(10)}${getSuffix(file.name)}`
        return file
      }
    
      const handleUploadChange = ({ file, fileList }) => {
        console.log(file, fileList)
        if (file.status === 'done') {
          if (file.response.code == 200) {
            message.success(`${file.name} 上传成功`);
            file.url = file.response.data;
          } else {
            message.warn(file?.response?.msg)
          }
          // if (accept.indexOf('video') != -1) {
          //   file.thumbUrl = file.url + fil;
          // }
        } else if (file.status === 'error') {
          message.error(`${file.name} 上传失败`);
        }
    
        fileList = fileList.filter(item => item.status);
        if (accept === '.apk') { //上传apk专用
          onChange(fileList)
        } else {
          onChange(fileList.map(item => item.url).filter(r => r).join(',') || undefined)
        }
        setFileList(fileList)
      }
    
      let previewProps = {}
      if (accept?.indexOf('image') != -1) { //目前仅针对图片利用Image组件4.7.0的新特性实现自定义预览
        previewProps = {
          onPreview: file => setPreviewSrc(file.url)
        }
      }
      if (accept?.indexOf('video') != -1) { //自定义的视频预览
        previewProps = {
          onPreview: file => {
            setVideoSrc(file.url)
            setClassNameVisible(true)
          }
        }
      }
    
      // 处理视频预览
      const [videoSrc, setVideoSrc] = useState(false)
      const [classNameVisible, setClassNameVisible] = useState(false)
      useEffect(() => {
        if (classNameVisible == false) {
          setTimeout(() => {
            setVideoSrc('')
          }, 200)
        }
      }, [classNameVisible]);
    
    
      const uploadComponent = (
        <Upload
          name='fileList'
          {...props}
          listType={listType}
          maxCount={maxCount}
          accept={accept}
          headers={function () {
            const timestamp = new Date().getTime()
            const rand = (Math.random() * 100).toFixed(0)
            return {
              'api-version': 1,
              token: sessionStorage.token || '',
              apiSecret: md5(md5(timestamp + 'ccys' + rand)),
              timestamp,
              rand
            }
          }()}
          // data={file => {
          //   return ({
          //     fileList: file
          //   })
          // }}
          action={uploadAction}
          multiple={maxCount > 1}
          fileList={fileList}
          onChange={handleUploadChange}
          beforeUpload={beforeUpload}
          onRemove={file => onRemove && onRemove(file)}
          {...previewProps}
        >
          {
            fileList.length >= maxCount ? null :
              (
                ['text', 'picture'].includes(listType) ?
                  <Button icon={<UploadOutlined />}>上传文件</Button> :
                  <div>
                    <PlusOutlined />
                    <div className="ant-upload-text">上传{accept.indexOf('video') != -1 ? '视频' : '图片'}{maxCount ? `(${fileList.length}/${maxCount})` : ''}</div>
                    {title ? <div>{title}</div> : null}
                  </div>
              )
          }
        </Upload>
      )
    
      const SortableItem = SortableElement(({ item }) => <Image style={{ cursor: 'move' }} preview={false} width={50} height={50} src={item.url} />);
      const SortableList = SortableContainer(() => {
        return (
          <Space className={styles.SortContainer}>
            {fileList.map((item, index) => (
              <SortableItem key={`item-${index}`} disabled={false} index={index} item={item} />
            ))}
          </Space>
        );
      });
      const uploadWrapRef = useRef()
      const SortableComponent = () => {
        //.uploadImg_sort的样式写在主要是定义zIndex为1000+,因为antd的modal层级为1000.目的是为了解决拖拽时元素看不见的问题
        return (
          <SortableList
            helperContainer={() => uploadWrapRef.current}
            helperClass="uploadImg_sort"
            lockOffset={0}
            transitionDuration={500} //拖拽过度动画时长
            lockToContainerEdges={true}
            axis="xy"
            onSortEnd={({ oldIndex, newIndex }) => {
              console.log(arrayMove(fileList, oldIndex, newIndex))
              const sortFileList = arrayMove(fileList, oldIndex, newIndex)
              onChange(sortFileList.map(item => item.url).filter(r => r).join(','))
              setFileList(sortFileList)
            }}
          />
        )
      }
    
      return (
        <div ref={uploadWrapRef} style={{ overflow: 'hidden' }} className={styles.uploadWrap}>
          {
            !!crop ?
              <>
                <ImgCrop rotate grid>
                  {uploadComponent}
                </ImgCrop>
                {supportSort && value?.length > 1 ? <SortableComponent /> : null}
              </>
              :
              <>
                {uploadComponent}
                {supportSort && value?.length > 1 ? <SortableComponent /> : null}
              </>
          }
          <Image
            width={0}
            height={0}
            src={previewSrc}
            preview={{
              visible: Boolean(previewSrc),
              onVisibleChange: (visible, prevVisible) => setPreviewSrc(undefined)
            }}
          />
          {
            videoSrc &&
            <div className={"ant-image-preview-mask " + (classNameVisible ? styles.videoPreviewMask : styles.videoPreviewMaskHide)} >
              <div className={"ant-image-preview-wrap " + (classNameVisible ? styles.videoPreviewWrap : styles.videoPreviewWrapHide)}>
                <ul className="ant-image-preview-operations">
                  <li className="ant-image-preview-operations-operation">
                    <CloseOutlined onClick={() => setClassNameVisible(false)} style={{ fontSize: 18, cursor: 'pointer' }} />
                  </li>
                </ul>
                <div className="ant-image-preview-img-wrapper" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={() => setClassNameVisible(false)}>
                  <video className="ant-image-preview-img" autoPlay controls poster={videoSrc + ossSuffix} src={videoSrc} onClick={e => e.stopPropagation()} />
                </div>
              </div>
            </div>
          }
        </div>
      )
    }
    
    export default GlobalUploadOss
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225

    less

    .SortContainer {
      width: 100%;
      display: flex;
      box-sizing: border-box;
      padding: 5px;
      background-color: #e6f7ff;
    }
    
    .uploadWrap {
      :global {
        .uploadImg_sort {
          z-index: 1001;
        }
    
        .ant-image-img {
          object-fit: contain;
        }
      }
    }
    
    
    @duration: 200ms;
    
    .videoPreviewMask {
      animation-name: fadeIn;
      animation-duration: @duration;
      animation-timing-function: linear;
    }
    
    
    @keyframes fadeIn {
      from {
        opacity: 0;
      }
    
      to {
        opacity: 1;
      }
    }
    
    .videoPreviewMaskHide {
      animation-name: fadeOut;
      animation-duration: @duration;
      animation-timing-function: linear;
    }
    
    @keyframes fadeOut {
      from {
        opacity: 1;
      }
    
      to {
        opacity: 0;
      }
    }
    
    .videoPreviewWrap {
      animation-name: scaleIn;
      animation-duration: @duration;
      animation-timing-function: ease-out;
    }
    
    
    @keyframes scaleIn {
      from {
        transform: scale(0);
      }
    
      to {
        transform: scale(1);
      }
    }
    
    .videoPreviewWrapHide {
      animation-name: scaleOut;
      animation-duration: @duration;
      animation-timing-function: ease-out;
    }
    
    @keyframes scaleOut {
      from {
        transform: scale(1);
      }
    
      to {
        transform: scale(0);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88

    引入

    在这里插入图片描述

  • 相关阅读:
    云原生技术 --- k8s配置组件之ConfigMap的学习与使用
    TDM+SDH+WDM+OTN+MPLS+PTN
    【cartographer_ros】七: 主要配置参数说明
    贪心算法之单源最短路径
    Postman如何做接口自动化测试?
    ISC技术分享:从BAS视角看积极防御体系实践
    java毕业设计体育训练队的信息管理系统服务端源码+lw文档+mybatis+系统+mysql数据库+调试
    Python教程:csv如何保存字典数据
    prim算法的实现
    数据结构———— 堆
  • 原文地址:https://blog.csdn.net/t_t2_3/article/details/126409011