<template>
<div>
<el-upload
action="#"
class="avatar-uploader"
:show-file-list="false"
:before-upload="beforeAvatarUpload"
:http-request="asd"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</template>
<script>
import { updateAvatarAPI } from '@/api/user'
export default {
data() {
return {
imageUrl: ''
}
},
methods: {
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
// console.log(file)
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && isLt2M
},
asd({ file }) {
// console.log(file)
const fd = new FileReader()
fd.readAsDataURL(file)
fd.onload = async () => {
this.imageUrl = fd.result
await updateAvatarAPI({ avatar: this.imageUrl })
}
}
}
}
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
使用element ui 里的upload 上传图片
最新推荐文章于 2024-01-19 20:17:41 发布
这是一个关于在Vue中实现头像上传功能的示例。代码通过el-upload组件进行文件上传,限制了上传文件必须为JPG格式且大小不超过2MB。在beforeAvatarUpload方法中进行了格式和大小的验证。当文件上传成功后,使用updateAvatarAPI更新头像,并通过FileReader读取文件内容转换为DataURL显示。
摘要由CSDN通过智能技术生成