//根据uid修改用户头像
Integer updateAvatarByUid(Integer uid, String modifiedUser, Date modifiedTime);
<update id="updateAvatarByUid">
UPDATE t_user SET avatar = #{avatar}, modified_user = #{modifiedUser}, modified_time = #{modifiedTime} WHERE uid = #{uid}
update>
@Test
public void updateAvatarByUid() {
userMapper.updateAvatarByUid(10, "/images/avatar/问号.png", "administrator", new Date());
}
/**
*修改用户的头像
* @param uid 用户id
* @param avatar 用户头像
* @param modifiedBy 修改者
*/
void changeAvatar(Integer uid,String avatar, String modifiedBy);
@Override
public void changeAvatar(Integer uid, String avatar, String modifiedBy) {
User result = userMapper.findByUid(uid);
if(result == null) {
throw new UserNotFoundException();
}
Integer rows = userMapper.updateAvatarByUid(uid, avatar, modifiedBy, new Date());
if(rows != 1) {
throw new UpdateException("修改用户头像时时产生了异常");
}
}
@Test
public void changeAvatar() {
userService.changeAvatar(10, "/images/testAvatar.png", "luck");
String avatar = userService.getByUid(10).getAvatar();
System.out.println(avatar);
}
所有异常都处理为FileUploadException
//限制文件类型
public static final ArrayList<String> AVATAR_TYPE = new ArrayList<>();
static {
AVATAR_TYPE.add("image/jpeg");
AVATAR_TYPE.add("image/png");
AVATAR_TYPE.add("image/bmp");
AVATAR_TYPE.add("image/gif");
}
/**
*
* @param session
* @param file
* @return
*/
@RequestMapping("/change_avatar")
public JsonResult<String> changeAvatar(HttpSession session,
@RequestParam("file") MultipartFile file) {
if(file.isEmpty()) {
throw new FileUploadException("文件为空");
}
String contentType = file.getContentType();
if(!AVATAR_TYPE.contains(contentType)) {
throw new FileUploadException("文件类型不支持");
}
//
String realPath = session.getServletContext().getRealPath("/upload");
File dir = new File(realPath);
if(!dir.exists()) {
dir.mkdirs();//创建当前目录
}
// 获取文件名称
String originalFilename = file.getOriginalFilename();
//获取文件名后缀
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
// 使用UUID随机生成一个新的文件名称前缀,拼接文件名称
String filename = UUID.randomUUID().toString().toUpperCase() + suffix;
//在指定位置创建一个空文件
File destFile = new File(dir, filename);
try {
file.transferTo(destFile);//将file文件中的数据写入到destFile中
} catch (IOException e) {
throw new FileUploadException("文件读写异常");
}
//返回头像路径/upload/test.png
String avatar = "/upload/" + filename;
userService.changeAvatar(getUidFromSession(session),avatar,getUsernameFromSession(session));
return new JsonResult<>(OK, avatar);
}
另外在配置文件中指定文件大小:
默认为1MB
spring.servlet.multipart.max-file-size=2MB
发送请求部分:
<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>