上传文件
请求:必须是POST请求
表单:enctype = "multipart/form-data"
Spring MVC:通过MultipartFile处理上传文件
开发步骤
访问账号设置页面
上传头像
获取头像
具体步骤
1、实现UserService的updateHeader方法
public int updateHeader(int userId, String headerUrl) { int rows = userMapper.updateHeader(userId, headerUrl); //Ed2.0 clearCache(userId); return rows; }
2、在controller中添加对应方法
@LoginRequired @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadHeader(MultipartFile headerImage, Model model) { if (headerImage == null) { model.addAttribute("error", "您还没有选择相片!"); return "/site/setting"; } String originalFilename = headerImage.getOriginalFilename(); String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); if (StringUtils.isBlank(suffix)) { model.addAttribute("error", "文件格式不正确!"); return "/site/setting"; } //生成随机文件名 String fileName = CommunityUtil.generateUUID() + new Random().nextInt(9999) + suffix; //确定文件存放的路径 //uploadPath在properties中设置为了本地硬盘,通过@Value取值 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; userService.updateHeader(user.getId(), headerUrl); return "redirect:/index"; } @RequestMapping(value = "/header/{fileName}", method = RequestMethod.GET) 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()); } } @LoginRequired @RequestMapping(value = "/modify", method = RequestMethod.POST) public String modifyPassword(String oldPassword, String newPassword, String confimPassword, Model model) { User user = hostHolder.getUser(); if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword) || StringUtils.isBlank(confimPassword)) { model.addAttribute("oldpasswordError", "密码输入有误,请重新输入!"); model.addAttribute("newpasswordError", "密码输入有误,请重新输入!"); model.addAttribute("confimpasswordError", "密码输入有误,请重新输入!"); return "/site/setting"; } if (!user.getPassword().equals(CommunityUtil.md5(oldPassword + user.getSalt()))) { model.addAttribute("oldpasswordError", "原密码输入错误,请重新输入!"); return "/site/setting"; } if (!newPassword.equals(confimPassword)) { model.addAttribute("newpasswordError", "两次密码输入不一致!"); model.addAttribute("confimpasswordError", "两次密码输入不一致!"); return "/site/setting"; } userService.updatePassword(user.getId(), CommunityUtil.md5(newPassword + user.getSalt())); return "redirect:/index"; }
3、前台代码
<!-- 上传头像 --> <h6 class="text-left text-info border-bottom pb-2">上传头像</h6> <form class="mt-5" method="post" enctype="multipart/form-data" th:action="@{/user/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':''}|" id="head-image" name="headerImage" lang="es" required=""> <label class="custom-file-label" for="head-image" data-browse="文件">选择一张图片</label> <div class="invalid-feedback" th:text="${error}"> A </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>