一、功能演示
二、需求分析
用戶上傳頭像是一個常見的功能,相信大家不會感到陌生。要實現這個功能大概有這些需求:
- 點擊“上傳頭像”佔位圖片後,彈出選擇本地圖片的窗口
- 選擇圖片後,在前端頁面預覽
- 點擊“開始上傳”按鈕,將圖片寫入用戶表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;
}
四、本篇小結
上傳頭像本質上是上傳文件,可以把上傳的圖片文件存到數據庫字段中;也可以把文件存到硬盤中,在數據庫中存放文件的路徑。因爲頭像文件不大,直接存放到數據庫中較爲直觀方便,所以我們這篇博客採用了這個方案。
關於前端部分的代碼,我們在後面的博客中介紹。
更多交流,歡迎加羣(584017112):