一、功能演示
二、需求分析
用户上传头像是一个常见的功能,相信大家不会感到陌生。要实现这个功能大概有这些需求:
- 点击“上传头像”占位图片后,弹出选择本地图片的窗口
- 选择图片后,在前端页面预览
- 点击“开始上传”按钮,将图片写入用户表BLOB字段中
- 上传成功后,更新前端的当前头像
不过,就是这么一个耳熟能详的功能,实现起来比上一节的修改用户信息还是要复杂很多滴~!毕竟,上传的头像是图片文件,相当于要处理:
- 前端的文件上传
- 前端图片展示
- BLOB字段的读写操作:后台数据库中头像的字段是BLOB类型,BLOB字段的更新比其它类型的也要复杂些
三、相关代码
代码分为前端和后端部分,为了保持合理篇幅,我们这篇博客先给大家介绍后端代码部分。
1. 数据库user表新增类型为mediumblob的字段profile
2. UserMapper.xml中增加profile字段的处理和更新头像方法updateProfileByUsername()
<resultMap id="ResultMapWithBLOBs" type="com.oms.model.User" extends="BaseResultMap">
<result column="profile" property="profile" jdbcType="LONGVARBINARY"
typeHandler="org.apache.ibatis.type.BlobTypeHandler"/>
</resultMap>
<!-- 根据username更新头像 -->
<update id="updateProfileByUsername" parameterType="com.oms.model.User">
update user
set profile = #{profile,jdbcType=LONGVARBINARY}
where username = #{username,jdbcType=VARCHAR}
</update>
3. User.java中增加profile变量和相应的get、set方法
private byte[] profile; //用户头像
public byte[] getProfile() {
return profile;
}
public void setProfile(byte[] profile) {
this.profile = profile;
}
4. UserController.java新增controller:updateHeadPic()
@ResponseBody
@RequestMapping(value = "/updateHeadPic")
public ResultObj updateHeadPic(HttpServletRequest request, HttpServletResponse response) {
String username = request.getSession().getAttribute("username").toString();
logger.info("/user/uploadHeadPic -> start - username: " + username);
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("profileFile");
logger.info("file content type: " + file.getContentType());
logger.info("file original name: " + file.getOriginalFilename());
logger.info("file name: " + file.getName());
if (null == file || file.isEmpty()) {
return new ResultObj("400", "文件不能为空");
}
ResultObj result = new ResultObj("200", "文件上传成功");
User u = new User();
try {
u.setUsername(username);
u.setProfile(file.getBytes());
result = userService.updateProfileByUsername(u);
} catch (Exception e) {
logger.error("上传失败 - " + e.getMessage());
result.setCode("500");
result.setMsg("文件保存失败");
}
logger.info("/user/updateHeadPic -> end");
return result;
}
5. UserServiceImpl.java新增方法:updateProfileByUsername()
@Transactional
public ResultObj updateProfileByUsername(User u) {
ResultObj result = new ResultObj();
int updated = userDao.updateProfileByUsername(u);
if (updated > 0) {
result.setCode("0");
result.setMsg("更新头像成功");
} else {
result.setCode("1");
result.setMsg("更新头像失败");
}
return result;
}
四、本篇小结
上传头像本质上是上传文件,可以把上传的图片文件存到数据库字段中;也可以把文件存到硬盘中,在数据库中存放文件的路径。因为头像文件不大,直接存放到数据库中较为直观方便,所以我们这篇博客采用了这个方案。
关于前端部分的代码,我们在后面的博客中介绍。
更多交流,欢迎关注公众号「小白轻松学编程」留言。
版权声明:本文为u012586848原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。