1.约束图片大小类型
//上传
let imageUrl = ref('')
let fileUploadCheck = (files) => {
let { type, size } = files.raw
if (size > 2 * 1024 * 1024) {
ElMessage({
message: '文件大小不能超过2M',
type: 'warning'
})
return
}
let allowType = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg']
if (!allowType.includes(type)) {
ElMessage({
message: '文件类型错误',
type: 'warning'
})
return
}
imageUrl.value = URL.createObjectURL(files.raw)
getBase64(files.raw)
console.log(formInline.value.img);
}
2.格式转换事件
let getBase64 = (file) => {
return new Promise(function (resolve, reject) {
const reader = new FileReader()
let imgResult: any = ''
reader.readAsDataURL(file)
reader.onload = function () {
imgResult = reader.result
formInline.value.img = imgResult
}
reader.onerror = function (error) {
reject(error)
}
reader.onloadend = function () {
resolve(imgResult)
}
})
}
3.绑定事件
<el-form-item label="图片">
<el-upload class="avatar-uploader"action="#":show-file-list="false":auto-upload="false"
@change="fileUploadcheck">
<img v-if="imageUrl":src="imageUrl" class="avatar" />
<el-icon v-else class="avatar-uploader-icon">
<Plus />
</el-icon>
</el-upload>
</el-form-item>