<template>
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>修改头像</span>
</div>
<!-- 图片预览 -->
<img :src="url" alt="" v-if="url" />
<img src="@/assets/images/avatar.jpg" alt="" ref="img" v-else />
<div>
<el-button type="primary" icon="el-icon-plus" @click="$refs.file.click()">选择图片</el-button>
<input type="file" ref="file" style="display: none" @change="fileChange" />
<el-button type="success" :disabled="url === ''" icon="el-icon-cloudy" @click="upload"
>上传头像</el-button
>
</div>
</el-card>
</template>
<script>
import { updateAvatarAPI } from '@/api/user'
export default {
data() {
return {
url: '' // 准备一个数据,用来保存base64格式的数据
}
},
methods: {
fileChange(e) {
// 判断是否选则了文件
if (e.target.files.length > 0) {
// 获取当前文件域的对象
const fl = e.target.files[0]
console.log(e.target.files)
// 实例一个FileReader对象
const fr = new FileReader()
fr.readAsDataURL(fl)
fr.onload = () => {
this.url = fr.result
// this.$refs.img.src = fr.result
}
} else {
this.url = ''
}
},
async upload() {
const { data: res } = await updateAvatarAPI({ avatar: this.url })
if (res.code === 0) {
// vuex重新获取数据
this.$message.success(res.$message)
this.$store.dispatch('user/gitUser')
}
}
}
}
</script>
<style lang="less" scoped>
img {
width: 350px;
height: 350px;
object-fit: cover;
}
</style>
eletemt http-request 上传图片
<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>