<template>
<div>
<el-upload
class="avatar-uploader"
:action="/api/toUpdateAvatar?userid=1"
:show-file-list="false"
accept=".jpg,.png"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl":src="imageUrl"class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload>
</div>
</template>
<script>
export default{
data(){
return{
imageUrl:'',
};
},
methods:{
handleAvatarSuccess(res, file){
this.imageUrl =ateObjectURL(file.raw);
},
beforeAvatarUpload(file){
//在头像上传之前需要做的判断,如判断⽂件格式const isJPG = pe ==='image/jpeg';
const isLt2M = file.size /1024/1024<2;
}
}
}
</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>
后端
/**
* 上传头像
* @param
* @param file
* @return
* @throws Exception
*/
@RequestMapping("/toUploadAvatar")
public MessageJson updatAvatar(User user,MultipartFile file)throws Exception{
//判断⽂件类型
String ContentType();
pType=pType.substring(pType.indexOf("/")+1);
if("jpeg".equals(pType)){
pType="jpg";
}
long time=System.currentTimeMillis();
//这⾥我采⽤绝对路径
String path="D:/(项⽬路径)/src/main/resources/static/images/avatar"+time+"."+pType;
try{
//⽂件路径保存到数据库中从⽽读取
userService.addVatar("192.168.191.3:8081/"+path.substring(path.indexOf("images/")),user);
}catch(Exception e){
e.printStackTrace();
}
return new MessageJson(SUCCESS,null);
}
解决上传⽂件访问不到的问题
访问不到刚刚上传的⽂件,主要是因为服务器并没有把刚刚的⽂件部署的Tomcat上,因此要配置⽂件访问的映射,具体操作如下: 1: 创建配置⽂件类,FileUploadConfig.java
2: 添加@Configuration注解,并实现WebMvcConfigurer接⼝
3: 重写WebMvcConfigurer的addResourcesHandlers⽅法
4: 配置映射,且映射路径以file开头
具体操作如下
@Configuration
public class FileUploadConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/images/**").
addResourceLocations("file:///D:/(项⽬存放路径)/src/main/resources/static/images/");
vue element admin//如果不知道如何以file开头就⽤浏览器打开该图⽚
}
}
亲测可⽤~~
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论