携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第7天,点击查看活动详情
账号设置
上传头像
1. 访问账号设置页面
访问很简单,就是写一个controller跳转到“账号设置页面”,然后修改一下**“账号设置页面”的路径即可,最后因为所有页面都使用了index.html,我们呢还要设置一下index.html头部的“账号设置”的路径**。
因为访问账号设置页面是属于用户的内容,所以我们新创建一个 UserController,在里面写访问“账号设置页面”的方法。
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(path = "/setting", method = RequestMethod.GET)
public String getSettingPage(){
return "/site/setting";
}
}
账号设置页面 setting.html
因为所有页面都复用了 index.html 的头部,我们要修改一下 index.html 头部的“账号设置” 的链接
访问账号设置页面写完之后建议启动项目测试一下
2. 上传头像
上传文件我们要在配置文件 application.properties 配置一下这个文件最终要存放到哪个硬盘上
注:文件上传路径必须存在,即 upload 必须存在
community.path.upload=d:/work/data/upload
数据访问层dao
因为之前更新头像的url之前写过,还有是把文件存到硬盘里,而不是数据库里,所以 数据访问层dao没有什么可做的。
业务层service
业务层service只处理更新路径的需求
public int updateHeader(int userId, String headerUrl){
return userMapper.updateHeader(userId, headerUrl);
}
表现层controller
表现层controller负责上传文件的动作
@Controller
@RequestMapping("/user")
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;
// 更新图片url需要用到 UserService
@Autowired
private UserService userService;
// 当前用户得从hostHoldear里取,所以注入 HostHolder
@Autowired
private HostHolder hostHolder;
// 访问“账号设置”页面
@RequestMapping(path = "/setting", method = RequestMethod.GET)
public String getSettingPage(){
return "/site/setting";
}
// 上传文件
// "上传"的表单的提交方式必须为POST
// MultipartFile 用来接收上传的文件,Model 用来给模板携带数据
@RequestMapping(path = "/upload", method = RequestMethod.POST)
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/community/user/header/xxx.png
User user = hostHolder.getUser();
String headerUrl = domain + contextPath + "/user/header/" + fileName;
headerUrl = headerUrl.replace(" ", "");
userService.updateHeader(user.getId(), headerUrl);
return "redirect:/index";
}
}
3. 获取头像
controller获取头像
UserController
// 获取头像
// 这个方法向浏览器响应的不是一个网页,不是一个字符串,而是一个图片,二进制的数据
// 我们需要通过流手动向浏览器输出,所以返回值为void,方法内部调response写
@RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
// 服务器存放路径
fileName = uploadPath + "/" + fileName;
// 文件后缀
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
// 响应图片
response.setContentType("image/" + suffix);
try (
// java7语法,在这里写的会自动在后面加上finally,执行close关闭方法
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());
}
}
配置setting.html表单