vue 上傳圖片限制寬高

//上傳之前
beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/gif'
          || file.type === 'image/jpg' || file.type === 'image/png'
          || file.type === 'image/GIF' || file.type === 'image/JPG' || file.type === 'image/bmp';
        // const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('圖片格式不正確!');
          return false
        }
        //如果要驗證寬高
        //this.validWidth  由上級組件傳入 props 接收
       //this.validHeight 由上級組件傳入 props 接收
        let validWidthAndHeight=true
        if(this.validWidth&&this.validHeight){
          return   this.valWidthAndHeight(file)
        }else return isJPG
      },

 //驗證圖片寬高
valWidthAndHeight:function(file){
		let _this =this
        return new Promise(function(resolve, reject) {
          let width = _this.validWidth  //圖片寬度
          let height = _this.validHeight ; //圖片高度
          let _URL = window.URL || window.webkitURL;
          let image = new Image();
          image.src = _URL.createObjectURL(file);
          image.onload = function() {
            let valid = image.width == width && image.height == height;
            valid ? resolve() : reject();
          };
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上傳圖片尺寸不符合,只能是"+_this.validWidth+"*"+_this.validHeight+"!");
            return Promise.reject();
          }
        );
      }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章