Vue element ui 限制上传图片比例

<el-upload
                class="avatar-uploader"
                action="http://************/file/upload"
                :show-file-list="false"
                name="image"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="form.attachment" :src="form.attachment" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                 <div slot="tip" class="el-upload__tip">封面图只能上传jpeg/png/jpg文件,且不超过500kb</div>
                </el-upload>

在上传图片之前

before-upload进行判断,注意判断顺序 return new Promise放最后
img.naturalWidth 和 img.naturalHeight 可以得到宽高,也可以限制图片具体像素大小
       beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' ||
                    file.type === 'image/jpg' ||
                    file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 5;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 jpeg/png/jpg 格式!');
                return  false 
            }else  if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 5MB!');
                return  false 
            }
           return new Promise((resolve,reject) => {
                let reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload = () => {
                    let img = new Image()
                    img.src = reader.result
                    img.onload = () => {
                        if (img.naturalWidth / img.naturalHeight !== 2) {
                            this.$message.error(`请上传宽高比为2:1的图片!`)
                            return reject(false)
                        } else {
                            return resolve(true)
                        }
                    }
                }
            })
        
      },

 

上一篇:年度最受欢迎的开源CHROME插件


下一篇:vue封装公共方法