头像上传
前言
后台系统一般会有用户个人信息的模块,为了增强用户的体验度,系统会开放自定义头像的功能,让用户可以上传自定义图片替代默认的系统头像。本文将通过SpringBoot+Vue来具体实现。
前端
<template>
<div>
<span style="margin-left: 160px" class="el-dropdown-links">
<el-upload
action="/sysUser/updateUrl"
:data="userForm.uid"
:show-file-list="false"
:on-success="onSuccess"
:before-upload="beforeUpload">
<img title="点击修改头像" :src="valueUrl"/>
</el-upload>
</span>
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
userForm: {//添加数据
uid: "1",
userName: "userAdmin",
password: "123456",
nickName: "李四",
sex: "",
avatar: "",
phoneNumber: "456421",
email: "295@qq.com",
userState: 1,
userDate: ""
},
valueUrl: '/image/abc-20220531052328174.jpg',
}
},
methods: {
// 上传图片
beforeUpload(file) {
if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
this.$notify.warning({
title: '警告',
message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
});
return false;
}
},
// 上传图片回显
onSuccess(res, file) {
if (file.response.code == 500) {
this.$message({
type: 'error',
message: file.response.message
});
} else {
this.$message({
type: 'success',
message: file.response.message
});
console.log("--1--",file);
// this.valueUrl = URL.createObjectURL(file.raw);
console.log("--2--",this.valueUrl);
// blob:http://localhost/ec6f040b-84b4-446a-9dd4-259b5f83789e
// this.$EventBus.$emit("switchTab",file.raw);
window.sessionStorage.setItem('avatar', file.response.obj);
}
},
}
}
</script>
<style>
.el-dropdown-links {
display: flex;
text-align: center;
line-height: 50px;
}
.el-dropdown-links img {
width: 100px;
height: 100px;
border-radius: 50px;
}
</style>
后端
package com.cs.admin;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.util.unit.DataSize;
import javax.servlet.MultipartConfigElement;
@SpringBootApplication
@MapperScan("com.cs.admin.mapper")
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 项目启动成功 ლ(´ڡ`ლ)゙ \n" +
" .-------. ____ __ \n" +
" | _ _ \\ \\ \\ / / \n" +
" | ( ' ) | \\ _. / ' \n" +
" |(_ o _) / _( )_ .' \n" +
" | (_,_).' __ ___(_ o _)' \n" +
" | |\\ \\ | || |(_,_)' \n" +
" | | \\ `' /| `-' / \n" +
" | | \\ / \\ / \n" +
" ''-' `'-' `-..-' ");
}
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//允许上传的文件最大值
factory.setMaxFileSize(DataSize.parse("50MB")); //KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize(DataSize.parse("50MB"));
return factory.createMultipartConfig();
}
}
package com.cs.admin.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation
.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置静态资源访问
*/
@Configuration
public class MvcWebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/image/**")//请求路径,相对路径
//转发路径,绝对路径
.addResourceLocations("file:" +
System.getProperty("user.dir") +
System.getProperty("file.separator") +
"src/main/resources/static/image/");
}
}
package com.example.admin.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.entity.SysUser;
import com.example.admin.service.SysUserService;
import com.example.admin.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* (SysUser)表控制层
*
* @author makejava
* @since 2022-05-23 17:33:13
*/
@Slf4j
@RestController
@RequestMapping("sysUser")
public class SysUserController {
/**
* 服务对象
*/
@Resource
private SysUserService sysUserService;
@PostMapping("updateUrl")
public Result setAvatar(MultipartFile file, int uid) throws IOException {
//判断图片是否为空
if (file.isEmpty()) {
return Result.error().message("上传图片为空");
}
//获取图片名称
String imgName = file.getOriginalFilename();
//获取图片后缀
String ss = imgName.substring(imgName.lastIndexOf("."));
//判断图片格式是否正确
if (!ss.equals(".jpg") && !ss.equals(".jpeg") && !ss.equals(".png")) {
return Result.error().message("图片格式不正确");
}
//获取图片前缀 + 时间 + 图片后缀
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");
String nowStr = imgName.substring(0, imgName.lastIndexOf(".")) + "-" + format.format(date);
//进行拼接,重新获取图片名称
String fileName = nowStr + imgName.substring(imgName.lastIndexOf("."));
//图片的路径
String names = "/image/" + fileName;
//获取图片存放的路径
String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "src\\main\\resources\\static" + File.separator + "image";
File file1 = new File(filePath);
//判断是否有文件夹,没有就创建一个文件夹
if (!file1.exists()) {
// file1.mkdir();
file1.getParentFile().mkdir();
file1.getAbsoluteFile().mkdir();
}
//把图片存放进去
File dest = new File(filePath + System.getProperty("file.separator") + fileName);
file.transferTo(dest);
//把图片路径存放到数据库
SysUser sysUser = new SysUser();
sysUser.setUid(uid);
sysUser.setAvatar(names);
// sysUserService.save(sysUser);
sysUserService.updateById(sysUser);
return Result.ok().data(names);
}
}