① HTML
<el-tooltip content="点击更换头像" placement="top">
<el-upload
class="avatar_uploader"
:action="uploadImgUrl"
:data="ImageData"
:show-file-list="false"
:headers="headers"
method="put"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img :src="userStore.avatar" />
</el-upload>
</el-tooltip>
属性释义:
action -- 对应向后端发起请求的完整API 包括测试地址在内
比如 http://192.168.1.0:8080/api/uploadHeadImage
http://192.168.1.0:8080 测试地址最好用一个全局变量代替 以防后面频繁更改麻烦
data -- 上传时携带的数据文件 这里即头像照片 写在before-upload事件里
show-file-list -- 是否显示已上传文件列表 默认为true 在上传多个文件里会用到 这里是头像(单个)故设置为false
header -- 请求头里的数据 看项目 一般带token即可
methods -- 上传方法 还是看接口文档 一般为put
on-success -- 上传成功后的后调事件
before-upload -- 上传前的回调事件 这里添加接口文档要求传的数据
② JS
<script setup>
//状态管理里面获取用户头像信息
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
// headers
const headers = ref({ "token": getToken() });
// 头像上传接口
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/api/setAvatar")
// 上传参数
const ImageData = ref()
// 上传之前
const beforeAvatarUpload = (rawFile) => {
if (rawFile.type !== "image/jpeg"&&rawFile.type !== "image/png"&&rawFile.type !== "image/jpg") {
ElMessage({
showClose:true,
message:'图片只能是JPG或PNG格式!',
type:'warning'
});
return;
}
if (rawFile.size / 1024 / 1024 > 5) {
ElMessage({
showClose:true,
message:'图片大小不能超过5MB!',
type:'warning'
});
return;
}
// 一般是formData格式
ImageData.value = new FormData();
// 'file'具体是什么字段看项目接口文档
ImageData.value.append('file',rawFile);
};
// 上传成功回调
const handleAvatarSuccess = (res, uploadFile) => {
userStore.avatar = URL.createObjectURL(uploadFile.raw);
};
</script>
CSS部分就不用展示了 图片大小和容器大小设置一样就行
效果: