Element UI upload 上傳圖片校驗格式 || 大小 || 比例


beforeAvatarUpload(file) {
  // 校驗圖片格式(也可直接用 accept 屬性限制如:accept="image/png,image/jpg,image/jpeg,image/gif")
  const isFormat = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif';
  // 校驗圖片大小
  const is200K = file.size / 1024 / 1024 < 0.196;

  if (!isFormat) {
    this.$message.error('上傳圖標只能為 jpg、png、gif 格式!');
    return false
  } else if (!is200K) {
    this.$message.error('上傳圖標大小不能超過 200K!');
    return false
  } else {
    // 校驗圖片寬高大小
    const isSize = new Promise((resolve, reject) => {
        const width = 18;
        const height = 18;
        const _URL = window.URL || window.webkitURL;
        const img = new Image();
        img.onload = () => {
            // 限制寬高必須為 18*18 像素
            const valid = img.width == width && img.height == height && img.width === img.height;
            // // 限制寬高必須為 1:1 比例
            // const valid = img.width == img.height;
            // // 限制必須為豎屏圖片(寬必須小於高)
            // const valid = img.width < img.height;
            // // 限制必須為橫屏圖片(寬必須大於高)
            // const valid = img.width > img.height;
            valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
    }).then(
        () => {
            return file;
        },
        () => {
            this.$message.error('上傳圖標尺寸限制為18*18比例');
            return Promise.reject();
        },
    );
    return isFormat && is200K && isSize
  }
  
  // return isFormat && is200K && isSize;
},

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM