antd upload组件使用

项目场景:

使用背景: 上传图片给服务器并且需要额外的传递参数
使用antd组件库,form表单下的upload组件

使用

图片上传自定义方法的使用,参数的上传
其中customRequest 作为自定义上传的方法与后端进行交互并可以传递额外的参数
beforeUpload 方法可以对上传的图片类型和大小做一下相对简单的前端校验

        <Upload
            name="uploadFile"
             listType="picture-card"
             className="avatar-uploader"
             showUploadList={false}
             fileList={fileList}
             customRequest={this.uploadHeadImg} //自定义上传的方法
             beforeUpload={this.beforeUpload}
             onChange={this.handleChange}
             >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>```
    uploadHeadImg =(option) => {
    const { pageTenantId } = this.state
    const formdata= new FormData();
    formdata.append('pageTenantId',pageTenantId);
    formdata.append('uploadFileName',option.file.name);
    formdata.append('uploadFile', option.file)
    axios.post('后端提供的接口',formdata,{headers:{
        "Content-Type": "application/x-www-form-urlencoded"
    }}).then(res=>{
        if(res.data.status==0) {
            option.onSuccess(res.data.data.returnParams.fileUrl)
            this.setState({
                logoUrl: res.data.data.returnParams.fileUrl
            })
        }
    }
  )
 }

onchange方法可以通过上传的状态对文件进行一些判断

     handleChange = async(info) => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
           await this.getBase64(info.file.originFileObj, imageUrl =>
            this.setState({
              imageUrl,
              loading: false,
              fileList:info.fileList,
            }), 
            );
        }
      };

beforeUpload的具体使用根据要求进行判断


    beforeUpload(file) {
        // 只允许图片的jpeg和png类型
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('图片类型只能为JPEG/PNG!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片不能大于2MB!');
        }
        return isJpgOrPng && isLt2M;
        }

在form表单中要使用getValueFromEvent对上传的文件数据赋值具体使用
在这里插入图片描述


normFile 方法 把文件return出来

    normFile = (e) => {
        this.setState({
            uploadFileName:e.file.name
        })
        if (Array.isArray(e)) {
          return e;
        }
        return e && e.fileList;
      };
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值