Echo/docs/70-账号设置.md

5.8 KiB
Raw Blame History

账号设置


修改头像(上传文件)

  • 请求:必须是 Post 请求
  • 表单enctype = "multipart/form-data"
  • Spring MVC通过 MultipartFile 处理上传文件

DAO

/**
 * 修改头像
 * @param id
 * @param headerUrl
 * @return
 */
int updateHeader(int id, String headerUrl);

Service

/**
 * 修改用户头像
 * @param userId
 * @param headUrl
 * @return
 */
public int updateHeader(int userId, String headUrl) {
     return userMapper.updateHeader(userId, headUrl);
}

Controller

@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());
        }
    }

其中:

try (
    FileInputStream fis = new FileInputStream(fileName);
    OutputStream os = response.getOutputStream();
) {
    
}

这样的写法的好处就是写在括号里的流会被自动的关闭不用我们在finally 里面手写关闭语句

前端

<form method="post" enctype="multipart/form-data" th:action="@{/user/upload}">
	
    <input type="file" th:class="|custom-file-input ${error != null ? 'is-invalid' : ''}|"
		   name="headerImage">
	<div class="invalid-feedback" th:text="${error}"></div>
<!--修改用户头像-->
<update id="updateHeader">
    update user set header_url = #{headerUrl} where id = #{id}
</update>

修改密码

DAO

/**
 * 修改密码
 * @param id
 * @param password 新密码
 * @return
 */
int updatePassword(int id, String password);
<!--修改密码-->
<update id="updatePassword">
    update user set password = #{password} where id = #{id}
</update>

Service

/**
 * 修改用户密码(对新密码加盐加密存入数据库)
 * @param userId
 * @param newPassword 新密码
 * @return
 */
public int updatePassword(int userId, String newPassword) {
    User user = userMapper.selectById(userId);
    newPassword = CommunityUtil.md5(newPassword + user.getSalt()); // 重新加盐加密
    return userMapper.updatePassword(userId, newPassword);
}

Controller

/**
 * 修改用户密码
 * @param oldPassword 原密码
 * @param newPassword 新密码
 * @param model
 * @return
 */
@PostMapping("/password")
public String updatePassword(String oldPassword, String newPassword, Model model) {
    // 验证原密码是否正确
    User user = hostHolder.getUser();
    String md5OldPassword = CommunityUtil.md5(oldPassword + user.getSalt());
    if (!user.getPassword().equals(md5OldPassword)) {
        model.addAttribute("oldPasswordError", "原密码错误");
        return "/site/setting";
    }

    // 判断新密码是否合法
    String md5NewPassword = CommunityUtil.md5(newPassword + user.getSalt());
    if (user.getPassword().equals(md5NewPassword)) {
        model.addAttribute("newPasswordError", "新密码和原密码相同");
        return "/site/setting";
    }

    // 修改用户密码
    userService.updatePassword(user.getId(), newPassword);

    return "redirect:/index";
}

前端

<form method="post" th:action="@{/user/password}">
    <input th:class="|form-control ${oldPasswordError != null ? 'is-invalid' : ''}|" 
           name = "oldPassword"  required>
	<div class="invalid-feedback" th:text="${oldPasswordError}"></div>