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;
},
 

猜你喜欢

转载自blog.csdn.net/GrootBaby/article/details/108443568