vue項目中,上傳圖片做像素大小寬高的限制

vue項目中,上傳圖片做像素大小寬高的限制

<el-upload
  class="avatar-uploader"
       action="http://upload.qiniup.com"
       :data="qn"
       :show-file-list="false"
       :on-success="handleAvatarSuccess"
       :before-upload="beforeAvatarUpload">
   <img v-if="form.joint.imgUrlBefore" :src="form.joint.imgUrlBefore"
        class="avatar" @click="getToken('imgUrlBefore','poster_url')">
   <i v-else class="el-icon-plus avatar-uploader-icon"
      @click="getToken('imgUrlBefore','poster_url')"></i>
</el-upload>
  /**
	*  上傳前判斷
	*/
	beforeAvatarUpload(file) {
	  
	   const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
	   const isLt1M = file.size / 1024 / 1024 < 1;
	
	   if (!isJPG) {
	       this.$message.error('上傳頭像圖片只能是 JPG/PNG 格式!');
	   }
	   if (!isLt1M) {
	       this.$message.error('上傳頭像圖片大小不能超過 1MB!');
	   }
	
	   let _this = this;
	   let imgWidth = "";
	   let imgHeight = "";
	   let width;
	   let height;
	   const isSize = new Promise(function (resolve, reject) {
	       if (_this.form.ad_type == 1) {
	           width = 700;
	           height = 300;
	       } else if (_this.form.ad_type == 2) {
	           width = 800;
	           height = 1280;
	       }
	       console.log(width, height);
	       let _URL = window.URL || window.webkitURL;
	       let img = new Image();
	       img.onload = function () {
	           imgWidth = img.width;
	           imgHeight = img.height;
	           let valid = img.width == width && img.height == height;
	           valid ? resolve() : reject();
	       };
	       img.src = _URL.createObjectURL(file);
	   }).then(
	       () => {
	           return file;
	       },
	       () => {
	           _this.$message.error({
	               message: '上傳文件的圖片大小不合符標準,寬需要爲' + width + 'px,高需要爲' + height + 'px。當前上傳圖片的寬高分別爲:' + imgWidth + 'px和' + imgHeight + 'px',
	               btn: false
	           });
	           return Promise.reject();
	       });
	   console.log(isSize);
	   return isJPG && isLt1M && isSize;
	},
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章