react antd-mobile ImagePicker实现对上传图片的限制

目的功能:
使用ImagePicker实现用户上传图片功能
当用户上传图片不是jpg/jpeg/png格式时,提醒用户,不允许上传其他格式的图片
当图片大于10M时,提醒用户,不允许上传图片大于10M的图片
并且需要把图片数据整合后再传给后台
条件可根据需求自行调整

一、ImagePicker的使用

                <ImagePicker
                  files={files}
                  onChange={this.uploadImg}
                  selectable={files.length < 6}
                />

二、state数据

    this.state = {
      files: [],//所有上传图片数据数组
      newFiles: [],//图片数据整合后的数组
    }

三、上传图片调用方法uploadImg

//files 用户上传图片的所有信息
//event add/remove事件
//index remove的索引
uploadImg = (files,event,index) => {

    const {newFiles} = this.state;
    const newImgFiles = JSON.parse(JSON.stringify(newFiles));

    // 用户添加图片
    if (event === 'add'){
      const imgType = files[files.length - 1].file.type;
      const imgSize = files[files.length - 1].file.size;
      const Filename = files[files.length - 1].file.name;

	  // 规定用户可以上传的图片类型
      if (imgType !== "image/jpeg" && imgType !== "image/png" && imgType !== "image/jpg"){
        Toast.info('请上传jpg/png格式的图片',1.5);
      } else if (imgSize > 10 * 1024 * 1024){// 规定图片大小尺寸
        Toast.info('请上传小于10M的图片',1.5);
      } else{
      // 筛选需要的图片数据
        const newImgItem = {};
        newImgItem.Filename = Filename;
        newImgItem.type = imgType;
        newImgItem.fileId = Math.random(0);

        if (imgSize < 1024 * 1024){
          newImgItem.size = (imgSize/1024).toFixed(2) + 'KB';
        } else {
          newImgItem.size = (imgSize/1024/1024).toFixed(2) + 'MB';
        }

        newImgFiles.push(newImgItem);
        this.setState({
          files,
          newFiles:newImgFiles
        });
      }
    }

    // 用户删除图片
    if (event === 'remove'){
      newImgFiles.splice(index,1);
      this.setState({
        files,
        newFiles:newImgFiles
      });
    }

    console.log(newImgFiles);

  };
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值