react之Ant Design upload上传图片 照片墙 使用Promise判断高宽

本文介绍了一个用于限制图片上传格式、尺寸和分辨率的方法。通过使用FileReader API读取图片数据,检查图片是否为JPG、JPEG或PNG格式,大小是否小于5MB,并验证其分辨率是否达到指定标准。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现限制图片上传格式、尺寸、分辨率的限制

  checkImageWH(file, width, height, resolve, reject) {
      let filereader = new FileReader();
      filereader.onload = e => {
        let src = e.target.result;
        const image = new Image();
        image.onload = function () {
          console.log(this.width, this.height)
          if ((width && this.width < width) || (height && this.height < height)) {
            if ((width && this.width < height) || (height && this.height < width)) {
              Modal.error({
                title: '分辨率请勿小于'+width+'*'+height+'或'+height+'*'+width
              })
              reject()
            } else {
              resolve();
            }
          } else {
            resolve();
          }
        };
        image.onerror = reject;
        image.src = src;
      };
      filereader.readAsDataURL(file);
  }
  handleBeforeUploads = file => {
    //限制图片 格式、size、分辨率
   const that= this
    return new Promise(function (resolve, reject) {
      const isJPG = file.type === 'image/jpg';
      const isJPEG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const bigLt2M = file.size / 1024 / 1024 < 5;
      // console.log(file);
      if (!(isJPG || isJPEG || isPNG)) {
        Modal.error({
          title: '只能上传JPG 、JPEG 、 PNG格式的图片~',
        });
        reject()
      } else if (!bigLt2M) {
        Modal.error({
          title: '请误超过5M',
        });
        reject()
      }else{
        that.checkImageWH(file, 480, 854, resolve, reject)
      }
    })
  };
              <Upload
                name="file"
                action={uploadAction}
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview} // 点击图片缩略图,进行预览
                beforeUpload={this.handleBeforeUploads} // 上传之前,对图片的格式做校验,并获取图片的宽高
                onChange={this.picChange}
              >
                {fileList.length >= 9 ? null : uploadButton}
              </Upload>

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值