限制上传图片格式,大小,比例代码
<template>
<div>
<!-- :show-file-list="false" -->
<el-upload
class="avatar-uploader"
action=""
accept=".png,.jpg,.gif"
:http-request="fnUploadRequest"
:before-upload="beforeAvatarUpload"
:show-file-list="false"
>
<img
v-if="ImgUrl"
:src="ImgUrl"
class="avatar"
alt=""
>
<i v-else class="el-icon-plus avatar-uploader-icon" />
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
ImgUrl: ''
}
},
methods: {
async fnUploadRequest(options) {
console.log('覆盖默认的上传行为,自定义上传', options)
},
/**
* 限制上传图片格式,大小,比例
* */
beforeAvatarUpload(file) {
console.log(file)
const isJpgPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
if (!isJpgPng) {
this.$message.error('上传文件格式只能是jpg/png/gif')
return false
}
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
return false
}
const isSize = new Promise(function(resolve, reject) {
const img = new Image()
img.onload = function() {
const valid = img.width / img.height === 1
valid ? resolve() : reject()
}
img.src = URL.createObjectURL(file)
}).then(() => {
return file
}, () => {
this.$message.error('上传图片比例只能为1:1, 请重新选择上传!')
return Promise.reject()
// return false
})
return isJpgPng && isLt2M && isSize
}
}
}
</script>
<style lang="scss" scope>
.avatarImg {
width: 178px;
height: 178px;
display: block;
background: #97a8be;
}
.hide .el-upload--picture-card {
display: none;
}
.el-upload--picture-card{
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 148px;
height: 148px;
line-height: 148px;
text-align: center;
}
}
.svgaView{
.el-icon-plus{
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
}
</style>