antd upload 文件上传状态控制 与from 表单数据绑定 问题记录

问题一: 组件上传后的数据如何跟表单的getFieldDecorator数据获取

问题二: 文件上传后的数据返回 接口全部在’done’状态下 如何实现 展示上传失败

问题三:自定义上传

使用antd组件开发是比较快速的开发方式,有时一些需求问题会遇到组件用起来不太方便,但是组件的样式又不想写,所以还是使用ANTD了
在upload 组件中遇到 上面的一些问题,所以做个记录 免得下次又查查查。。。。

默认上传 upload上传默认是FormFata 格式,如果使用组件的请求上传

 <Upload
            name='file'
            listType='text'
            multiple={true}
            action={'请求地址'}
            accept="image/gif,image/jpeg,image/jpg,image/png,image/svg,image/webp"
            data={ {
               需要的新增的参数
              } }
            headers={{
              这里一般是接口需要的认证信息 ,在axios 封装的时候会设置好,如果使用upload的请求 就需要添加上
            }}
            onChange={ ({ file, fileList }) => {
                if (file.status === 'done') {
                  if (file.response.code !== '0') {
                    message.warning(file.response.message)
                  }
                }
                return fileList
              }
            }
            beforeUpload={beforeUpload}
          >
            <Button>
              <Icon type="upload" />上传文件
            </Button>
            <span className="ant-form-text">支持扩展名:.rar .zip .doc .docx .pdf .jpg</span>
          </Upload>

自定义上传
这一块就是使用customRequest 属性 去截取原生请求 写了这个参数 action 就会失效

<Upload
  // 自定义上传 (可完全自定义处理返回) 二者互不兼容
      customRequest: (e) => {
        this.postUpload(e)
      }
      // 组件上传 (无法捕获 自定义错误信息)
      name: 'file'
      // action: `${configApi.Sup}/api/ProductAllowance/UploadAllowanceProducts`,
      accept: ".xlsx, .xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      multiple: false
      data: {
     {
     		这里写的Data 在自定义的请求里面 的e 里都可以结构出来
     }
      }
      >
      </Upload>

文件上传后的数据返回 接口全部在’done’状态下 如何实现 展示上传失败

这个问题是比较常见的, 由于后端接口的返回是统一的 所以 失败了也是在reaponse 里面告诉前端 这个图片失败了 ,除非接口i出错 才会走到 onChange里面的 Error 步骤

onChange 三个状态 Uploding ,done , error

当我们与form 表单组合使用时(不好描述 直接代码。。。。)
1、


    <Form.Item label="电子发票上传" className='uploadClass'>
        {getFieldDecorator('electronicInvoice', {
          valuePropName: 'fileList', /// 这里是转换 绑定的参数的  form 获取的是value  而upload  返回的是fileList
          getValueFromEvent: normFile, //把onchange的数据转成表单的值  就是处理 失败的问题返回 看下面的函数处理
          initialValue: []
        })(
          <Upload
            name='file'
            listType='text'
            multiple={true}
            action={`url`}
            accept="image/gif,image/jpeg,image/jpg,image/png,image/svg,image/webp"
            data={{   }}
            headers={{  }}
            onChange={
              ({ file, fileList }) => {
              这里就是接口成功回调
                if (file.status === 'done') {
                // 接口成功 返回 内部参数告诉失败
                  // 此处处理整体返回数据
                  if (file.response.code !== '0') {
                    message.warning(file.response.message)
                  }
                }
                return fileList
              }
            }
            beforeUpload={beforeUpload} //过滤不需要的请求 比如文件格式不对,文件大小超了等。。。。
          >
            <Button>
              <Icon type="upload" />上传文件
            </Button>
            <span className="ant-form-text">支持扩展名:.rar .zip .doc .docx .pdf .jpg</span>
          </Upload>
        )}

      </Form.Item>


/---------------------------------/

  const normFile = e => {
    const { file, fileList } = e
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }

    if (file.status === 'done') {
      // 此处处理整体返回数据
      return standardization(fileList)
    }
    return e && fileList

  };

// 将fileList 处理成upload 展示的格式  state='done' 就是成功 ,  state='error' 是失败
// 序列化upload 数据 设置到表单后  就会对应展示
  const standardization = arr => {
    let resArr = []
    arr.forEach((item) => {
      if (item.response.code === '0') {
        let obj = {
          uid: item.uid,
          name: item.name,
          status: 'done',
          response: item.response, // custom error message to show
          url: ''
        }
        resArr.push(obj)
      } else { // 后面应该不处理 失败了 不应展示 所以可以直接去掉
        let obj = {
          uid: item.uid,
          name: item.name,
          status: 'error',
          response: item.response, // custom error message to show
          url: item.thumbUrl || item.url
        }
        resArr.push(obj)
      }
    })
    return resArr
  }


关键点:  1、 Form。item 的两个参数  
			valuePropName: 'fileList',  //

// 可以这里获取form的数据
	 form.validateFields((err, values) => {
      	console.log(err, values, '获取到的表单数据')
      if (!err) {
        confirmInvoicing(values)
      }
    })

  getValueFromEvent: normFile, //处理如何展示 成功还是失败


处理上传失败 以及 禁止上传时 返回的数据

场景: 上传失败不展示 、超出最大上传限制时 beforeUpload返回false 时 过滤数据 并设置到表单

  const normFile = e => {
    const { file, fileList } = e
    console.log('数据变化:', e);
    if (Array.isArray(e)) {
      return e;
    }
    // if (file.status) {
    // if (file.status == 'uploading') {
    //   return fileList
    // }
    if (file.status === 'done') {
      // 此处处理整体返回数据
      return standardization(fileList)
    }
    if (!file.status) {
      return fileList.filter((item) => {
        return item.status == 'done'
      })
    }
    return fileList
  };
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值