效果图:
实现方法:
!!!用于回显的关键代码:URL.createObjectURL(file.raw)
html:
<el-upload class="avatar-uploader"
:action="''"
:auto-upload="false" //取消自动上传
:show-file-list="false"
:on-change="handleAvatarChangeIcon">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
methods:
handleAvatarChangeIcon(file, fileList) {//选中文件触发的change事件
// console.log(file)
const isJPG = file.raw.type === 'image/jpeg'
const isPNG = file.raw.type === 'image/png'
// const isLt2M = file.raw.size / 1024 / 1024 < 0.5 //限制上传文件的大小
if (!isPNG && !isJPG) {
this.$message.error('上传图片只能是 JPG/PNG 格式!')
return false
} else {
this.imageUrl = URL.createObjectURL(file.raw);//赋值图片的url,用于图片回显功能
this.uploadImg(file)//调用上传文件api接口
}
}
uploadImg(file){//文件上传操作
let formData=new FormData()
formData.append('file',file.raw)
uploadImg(formData).then(res=>{
if (res.code == '200') {
console.log('图片上传成功')
}
})
}
export function uploadImg(params) {
return axios.post('/api/xxx/xxx/simple/upload',params,{
headers: {'Content-Type':'multipart/form-data'}
})
}