餓了麼el-upload上傳圖片限制圖片尺寸、大小、格式

餓了麼中的Upload組件已經提供了限制用戶上傳的圖片格式和大小的例子(https://element.eleme.io/#/zh-CN/component/upload),在此又新加圖片的尺寸

<el-upload
  class="avatar-uploader"
  action=""
  :show-file-list="false"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

before-upload

上傳文件之前的鉤子,參數爲上傳的文件,若返回 false 或者返回 Promise 且被 reject,則停止上傳。

主要就是在上傳之前做一些判斷處理 

<script>
  export default {
    data() {
      return {
        imageUrl: ''
      };
    },
    methods: {
      // 文件上傳之前做處理
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        // 圖片格式
        if (!isJPG) {
          this.$message.error('上傳頭像圖片只能是 JPG 格式!');
          return false;
        }
        // 圖片大小
        if (!isLt2M) {
          this.$message.error('上傳頭像圖片大小不能超過 2MB!');
          return false;
        }
        // 圖片尺寸
        let imgWidth="";
        let imgHight="";
        const isSize = new Promise(function (resolve, reject) {
            const _URL = window.URL || window.webkitURL;
            const img = new Image();
            img.onLoad = function () {
                imgWidth = img.width;
                imgHight = img.height;
                const status = img.width === 240 && img.height === 240;
                status ? resolve() : reject();
            }
            img.src = _URL.createObjectURL(file);
        }).then(()=>{
            this.uploadImg(file);    // 調用後臺接口上傳圖片的方法
        }).catch(()=>{
            this.$message.warning({message: '上傳文件的圖片大小不合符標準,尺寸爲240×240。當前上傳圖片的尺寸爲:'+imgWidth+'×'+imgHight})
        })
      },
      async uploadImg(file) {
            const result = await equityManagementModels.getImageUrl(file);
            this.imageUrl = result;
      },
    }
  }
</script>

 

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