7、账号设置/setting
上传头像将头像保存到本地/七牛云服务器,随机生成字符串作为图片的名称,表单提交再返回该界面。获取头像时,在本地获取,通过输入输出流,先读到缓冲区,再从缓冲区写出;在七牛云服务器获取时,不使用流的方式,直接通过文件名获取,将header的URL更新在user用户中。
8、更改密码/changePassword:表单提交新密码,判断密码是否符合标准,更新user信息,并退出登录,重定向到登录界面重新登录
---------------------------------------------------------------------------------------------------------------------------------
1.UserController:
package com.nowcoder.community.controller;
import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserServiceImpl;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@Controller
public class UserController {
private static final Logger logger= LoggerFactory.getLogger(UserController.class);
@Value("${community.path.upload}")
private String uploadPath;
@Value("${community.path.domain}")
private String domain;
@Value("${server.servlet.context-path}")
private String contextPath;
@Autowired
private UserServiceImpl userService;
@Autowired
private HostHolder hostHolder;
@LoginRequired
@GetMapping("/setting")
public String getSettingPage(){
return "/site/setting";
}
@LoginRequired
@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 file1 = new File(uploadPath);
if (!file1.exists()){
file1.mkdir();
}
File file = new File(file1 + "/" + fileName);
try {
//存储文件
headerImage.transferTo(file);
} catch (IOException e) {
logger.error("上传文件失败:"+e.getMessage());
throw new RuntimeException("上传文件失败,服务器发生异常!",e);
}
//更新当前用户的头像路径(web访问路径)
// http://localhost:8080/community/header/xxx.png
User user = hostHolder.getUser();
String headerUrl=domain+contextPath+"/header/"+fileName;
userService.updateHeader(user.getId(),headerUrl);
return "redirect:/index";
}
@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);
ServletOutputStream os = response.getOutputStream();)
{
byte[] bytes=new byte[1024];
int len=0;
while ((len=fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
logger.error("读取头像失败:"+e.getMessage());
}
}
@LoginRequired
@PostMapping("/updatePassword")
public String updatePassword(String originalPassword,String newPassword,String confirmPassword,Model model){
if (originalPassword==null){
model.addAttribute("originalPasswordMsg","请输入原始密码!");
return "/site/setting";
}
if (newPassword==null){
model.addAttribute("newPasswordMsg","请输入新密码!");
return "/site/setting";
}
if (confirmPassword==null){
model.addAttribute("confirmPasswordMsg","请确认密码!");
return "/site/setting";
}
//确认账号
User user = hostHolder.getUser();
if (!CommunityUtil.md5(originalPassword+user.getSalt()).equals(user.getPassword())){
model.addAttribute("originalPasswordMsg","密码错误!");
return "/site/setting";
}
if (!confirmPassword.equals(newPassword)){
model.addAttribute("confirmPasswordMsg","两次输入的密码不一致!");
return "/site/setting";
}
userService.updatePassword(user.getId(),CommunityUtil.md5(newPassword+user.getSalt()));
return "redirect:/index";
}
}
2.setting.html
<form class="mt-5" method="post" enctype="multipart/form-data" th:action="@{/upload}">
<div class="form-group row mt-4">
<label for="head-image" class="col-sm-2 col-form-label text-right">选择头像:</label>
<div class="col-sm-10">
<div class="custom-file">
<input type="file" th:class="|custom-file-input ${error!=null ? 'is-invalid' : ''}|" name="headerImage" id="head-image" lang="es" required="">
<label class="custom-file-label" for="head-image" data-browse="文件">选择一张图片</label>
<div class="invalid-feedback" th:text="${error}">
该账号不存在!
</div>
</div>
</div>
</div>
<div class="form-group row mt-4">
<div class="col-sm-2"></div>
<div class="col-sm-10 text-center">
<button type="submit" class="btn btn-info text-white form-control">立即上传</button>
</div>
</div>
</form>