diff --git a/docs/70-账号设置.md b/docs/70-账号设置.md new file mode 100644 index 00000000..08669236 --- /dev/null +++ b/docs/70-账号设置.md @@ -0,0 +1,233 @@ +# 账号设置 + +--- + +## 修改头像(上传文件) + +- 请求:必须是 Post 请求 +- 表单:enctype = "multipart/form-data" +- Spring MVC:通过 MultipartFile 处理上传文件 + +### DAO + +```java +/** + * 修改头像 + * @param id + * @param headerUrl + * @return + */ +int updateHeader(int id, String headerUrl); +``` + + + +### Service + +```java +/** + * 修改用户头像 + * @param userId + * @param headUrl + * @return + */ +public int updateHeader(int userId, String headUrl) { + return userMapper.updateHeader(userId, headUrl); +} +``` + +### Controller + +```java +@Controller +@RequestMapping("/user") +public class UserController { + + ...... + + /** + * 修改用户头像 + * @param headerImage + * @param model + * @return + */ + @PostMapping("/upload") + public String uploadHeader(MultipartFile headerImage, Model model) { + if (headerImage == null) { + model.addAttribute("error", "您还没有选择图片"); + return "/site/setting"; + } + + // 获取文件后缀名 + String fileName = headerImage.getOriginalFilename(); + String suffix = fileName.substring(fileName.lastIndexOf(".")); // 文件后缀名 + if (StringUtils.isBlank(suffix)) { + model.addAttribute("error", "图片文件格式不正确"); + return "/site/setting"; + } + + // 对用户上传的图片文件进行重新随机命名 + fileName = CommunityUtil.generateUUID() + suffix; + // 确定文件存放的路径 + File dest = new File(uploadPath + "/" + fileName); + try { + // 存储图片文件 + headerImage.transferTo(dest); + } catch (IOException e) { + logger.error("上传文件失败" + e.getMessage()); + throw new RuntimeException("上传文件失败,服务器发生异常", e); + } + + // 更新当前用户的头像的路径(web 访问路径) + // http://localhost:8080/echo/user/header/xxx.png + User user = hostHolder.getUser(); + String headUrl = domain + contextPath + "/user/header/" + fileName; + userService.updateHeader(user.getId(), headUrl); + + return "redirect:/index"; + + } + + /** + * 响应/显示用户上传的图片文件 + * 即解析当前用户头像的路径(web 访问路径)http://localhost:8080/echo/user/header/fileName + * @param fileName + * @param response + */ + @GetMapping("/header/{fileName}") + public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) { + // 图片存放在服务器上的路径 + fileName = uploadPath + "/" + fileName; + // 图片文件后缀名 + String suffix = fileName.substring(fileName.lastIndexOf(".")); + // 响应图片 + response.setContentType("image/" + suffix); + try ( + FileInputStream fis = new FileInputStream(fileName); + OutputStream os = response.getOutputStream(); + ) { + byte[] buffer = new byte[1024]; + int b = 0; + while ((b = fis.read(buffer)) != -1) { + os.write(buffer, 0, b); + } + } catch (IOException e) { + logger.error("读取文件失败" + e.getMessage()); + } + } +``` + +其中: + +```java +try ( + FileInputStream fis = new FileInputStream(fileName); + OutputStream os = response.getOutputStream(); +) { + +} +``` + +这样的写法的好处就是:写在括号里的流会被自动的关闭,不用我们在finally 里面手写关闭语句 + +### 前端 + +```html +