🍁
博客主页:👉@不会压弯的小飞侠
✨欢迎关注:👉点赞👍收藏⭐留言✒
✨系列专栏:👉SpringBoot电商项目实战
✨学习社区:👉不会压弯的小飞侠
✨知足上进,不负野心。
🔥欢迎大佬指正,一起学习!一起加油!

/**
* 根据uid更新用户的头像
* @param uid 用户的id
* @param avatar 新头像的路径
* @param modifiedUser 修改执行人
* @param modifiedTime 修改时间
* @return 受影响的行数
*/
Integer updateAvatarByUid(
@Param("uid") Integer uid,
@Param("avatar") String avatar,
@Param("modifiedUser") String modifiedUser,
@Param("modifiedTime") Date modifiedTime);
<!-- 根据uid更新用户的头像-->
<update id="updateAvatarByUid">
UPDATE
t_user
SET
avatar = #{avatar},
modified_user = #{modifiedUser},
modified_time = #{modifiedTime}
WHERE
uid = #{uid}
</update>
@Test
public void updateAvatarByUid() {
Integer uid = 11;
String avatar = "/upload/avatar.png";
String modifiedUser = "管理员";
Date modifiedTime = new Date();
Integer rows = userMapper.updateAvatarByUid(uid, avatar, modifiedUser, modifiedTime);
System.out.println("rows=" + rows);
}

/**
* 修改用户头像
* @param uid 当前登录的用户的id
* @param username 当前登录的用户名
* @param avatar 用户的新头像的路径
*/
void changeAvatar(Integer uid, String username, String avatar);
@Override
public void changeAvatar(Integer uid, String username, String avatar) {
// 调用userMapper的findByUid()方法,根据参数uid查询用户数据
User result = userMapper.findByUid(uid);
// 检查查询结果是否为null
if (result == null) {
// 是:抛出UserNotFoundException
throw new UserNotFoundException("用户数据不存在");
}
// 检查查询结果中的isDelete是否为1
if (result.getIsDelete().equals(1)) {
// 是:抛出UserNotFoundException
throw new UserNotFoundException("用户数据不存在");
}
// 创建当前时间对象
Date now = new Date();
// 调用userMapper的updateAvatarByUid()方法执行更新,并获取返回值
Integer rows = userMapper.updateAvatarByUid(uid, avatar, username, now);
// 判断以上返回的受影响行数是否不为1
if (rows != 1) {
// 是:抛出UpdateException
throw new UpdateException("更新用户数据时出现未知错误,请联系系统管理员");
}
}
@Test
public void changeAvatar() {
Integer uid = 11;
String username = "lll";
String avatar = "/upload/change.png";
iUserService.changeAvatar(uid, username, avatar);
}

/** 文件上传相关异常的基类 */
public class FileUploadException extends RuntimeException {
public FileUploadException() {
super();
}
public FileUploadException(String message) {
super(message);
}
public FileUploadException(String message, Throwable cause) {
super(message, cause);
}
public FileUploadException(Throwable cause) {
super(cause);
}
protected FileUploadException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
// 上传的文件为空
com.jkj.controller.ex.FileEmptyException
// 上传的文件大小超出了限制值
com.jkj.store.controller.ex.FileSizeException
// 上传的文件类型超出了限制
com.jkj.store.controller.ex.FileTypeException
// 上传的文件状态异常
com.jkj.store.controller.ex.FileStateException
// 上传文件时读写异常
com.jkj.store.controller.ex.FileUploadIOException
/** 上传的文件为空的异常,例如没有选择上传的文件就提交了表单,或选择的文件是0字节的空文件 */
public class FileEmptyException extends FileUploadException {
public FileEmptyException() {
super();
}
public FileEmptyException(String message) {
super(message);
}
public FileEmptyException(String message, Throwable cause) {
super(message, cause);
}
public FileEmptyException(Throwable cause) {
super(cause);
}
protected FileEmptyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@ExceptionHandler({ServiceException.class, FileUploadException.class})
public JsonResult<Void> handleException(Throwable e) {
JsonResult<Void> result = new JsonResult<Void>(e);
if (e instanceof UsernameDuplicateException) {
result.setState(4000);
} else if (e instanceof UserNotFoundException) {
result.setState(4001);
} else if (e instanceof PasswordNotMatchException) {
result.setState(4002);
} else if (e instanceof InsertException) {
result.setState(5000);
} else if (e instanceof UpdateException) {
result.setState(5001);
} else if (e instanceof FileEmptyException) {
result.setState(6000);
} else if (e instanceof FileSizeException) {
result.setState(6001);
} else if (e instanceof FileTypeException) {
result.setState(6002);
} else if (e instanceof FileStateException) {
result.setState(6003);
} else if (e instanceof FileUploadIOException) {
result.setState(6004);
}
return result;
}
/** 头像文件大小的上限值(10MB) */
public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;
/** 允许上传的头像的文件类型 */
public static final List<String> AVATAR_TYPES = new ArrayList<String>();
/** 初始化允许上传的头像的文件类型 */
static {
AVATAR_TYPES.add("image/jpeg");
AVATAR_TYPES.add("image/png");
AVATAR_TYPES.add("image/bmp");
AVATAR_TYPES.add("image/gif");
}
@PostMapping("change_avatar")
public JsonResult<String> changeAvatar(@RequestParam("file") MultipartFile file, HttpSession session) {
// 判断上传的文件是否为空
if (file.isEmpty()) {
// 是:抛出异常
throw new FileEmptyException("上传的头像文件不允许为空");
}
// 判断上传的文件大小是否超出限制值
if (file.getSize() > AVATAR_MAX_SIZE) { // getSize():返回文件的大小,以字节为单位
// 是:抛出异常
throw new FileSizeException("不允许上传超过" + (AVATAR_MAX_SIZE / 1024) + "KB的头像文件");
}
// 判断上传的文件类型是否超出限制
String contentType = file.getContentType();
// public boolean list.contains(Object o):当前列表若包含某元素,返回结果为true;若不包含该元素,返回结果为false。
if (!AVATAR_TYPES.contains(contentType)) {
// 是:抛出异常
throw new FileTypeException("不支持使用该类型的文件作为头像,允许的文件类型:\n" + AVATAR_TYPES);
}
// 获取当前项目的绝对磁盘路径
String parent = session.getServletContext().getRealPath("upload");
// 保存头像文件的文件夹
File dir = new File(parent);
if (!dir.exists()) {
dir.mkdirs();
}
// 保存的头像文件的文件名
String suffix = "";
String originalFilename = file.getOriginalFilename();
int beginIndex = originalFilename.lastIndexOf(".");
if (beginIndex > 0) {
suffix = originalFilename.substring(beginIndex);
}
String filename = UUID.randomUUID().toString() + suffix;
// 创建文件对象,表示保存的头像文件
File dest = new File(dir, filename);
// 执行保存头像文件
try {
file.transferTo(dest);
} catch (IllegalStateException e) {
// 抛出异常
throw new FileStateException("文件状态异常,可能文件已被移动或删除");
} catch (IOException e) {
// 抛出异常
throw new FileUploadIOException("上传文件时读写错误,请稍后重尝试");
}
// 头像路径
String avatar = "/upload/" + filename;
// 从Session中获取uid和username
Integer uid = getUidFromSession(session);
String username = getUsernameFromSession(session);
// 将头像写入到数据库中
userService.changeAvatar(uid, username, avatar);
// 返回成功头像路径
return new JsonResult<String>(OK, avatar);
}

@Bean
public MultipartConfigElement getMultipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// DataSize dataSize = DataSize.ofMegabytes(10);
// 设置文件最大10M,DataUnit提供5中类型B,KB,MB,GB,TB
factory.setMaxFileSize(DataSize.of(10, DataUnit.MEGABYTES));
factory.setMaxRequestSize(DataSize.of(10, DataUnit.MEGABYTES));
// 设置总上传数据总大小10M
return factory.createMultipartConfig();
}
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB
<script type="text/javascript">
$("#btn-change-avatar").click(function() {
$.ajax({
url: "/users/change_avatar",
type: "POST",
data: new FormData($("#form-change-avatar")[0]),
dataType: "JSON",
processData: false, // processData处理数据
contentType: false, // contentType发送数据的格式
success: function(json) {
if (json.state == 200) {
$("#img-avatar").attr("src", json.data);
} else {
alert("修改失败!" + json.message);
}
},
error: function(xhr) {
alert("您的登录信息已经过期,请重新登录!HTTP响应码:" + xhr.status);
location.href = "login.html";
}
});
});
</script>
$("#btn-login").click(function() {
$.ajax({
url: "/users/login",
type: "POST",
data: $("#form-login").serialize(),
dataType: "json",
success: function(json) {
if (json.state == 200) {
alert("登录成功!");
$.cookie("avatar", json.data.avatar, {expires: 7});
console.log("cookie中的avatar=" + $.cookie("avatar"));
location.href = "index.html";
} else {
alert("登录失败!" + json.message);
}
}
});
});
语法:$.cookie(名称,值,[option])。[option]参数说明:
在upload.html页面中,默认并没有引用jqueyr.cookie.js文件,因此无法识别$.cookie()函数;所以需要在upload.html页面head标签内添加jqueyr.cookie.js文件。
<script src="../bootstrap3/js/jquery.cookie.js" type="text/javascript" charset="utf-8"></script>
$(document).ready(function () {
console.log("cookie中的avatar=" + $.cookie("avatar"));
$("#img-avatar").attr("src", $.cookie("avatar"));
});
$.cookie("avatar", json.data, {expires: 7});
<script type="text/javascript">
$(document).ready(function () {
console.log("cookie中的avatar=" + $.cookie("avatar"));
$("#img-avatar").attr("src", $.cookie("avatar"));
});
$("#btn-change-avatar").click(function() {
$.ajax({
url: "/users/change_avatar",
type: "POST",
data: new FormData($("#form-change-avatar")[0]),
dataType: "JSON",
processData: false, // processData处理数据
contentType: false, // contentType发送数据的格式
success: function(json) {
if (json.state == 200) {
$("#img-avatar").attr("src", json.data);
$.cookie("avatar", json.data, {expires: 7});
} else {
alert("修改失败!" + json.message);
}
},
error: function(xhr) {
alert("您的登录信息已经过期,请重新登录!HTTP响应码:" + xhr.status);
location.href = "login.html";
}
});
});
</script>

学习视频:
【SpringBoot项目实战完整版】SpringBoot+MyBatis+MySQL电脑商城项目实战-哔哩哔哩】
https://b23.tv/qGh9x9L
