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

 


免責聲明!

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



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