天天看點

react之Ant Design upload上傳圖檔 照片牆 使用Promise判斷高寬

實作限制圖檔上傳格式、尺寸、分辨率的限制

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>