Antd Upload圖片上傳之前使用promise進行寬高的校驗

在寫需求的時候要進行寬高的校驗,再進行上傳,可以使用promise來進行判斷,是繼續resolve()還是reject()
使用示例 (直接上代碼)

beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M && this.checkImageWH(file, 710, 180);
  }

  checkImageWH(file, width, height) {
    let self = this;
    return new Promise(function (resolve, reject) {
        let filereader = new FileReader();
        filereader.onload = e => {
            let src = e.target.result;
            const image = new Image();
            image.onload = function () {
                if (width && this.width != width || height && this.height != height) {
                    message.error(
                         '請上傳' + width + "*"+  height + '的圖片'
                    )
                    reject();
                } else {
                    resolve();
                }
            };
            image.onerror = reject;
            image.src = src;
        };
        filereader.readAsDataURL(file);
    });
}


  <Upload
          name="avatar"
                className = {styles.inlinebannerpic}
                listType="picture-card"
                showUploadList={false}
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange}
              >
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>

方便以後直接複用!!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章