@RequestMapping("/updateAvatar.html") public String updateHeadUrl(MultipartFile avatar, Model model, HttpSession session) throws IOException { // 文件类型限制 String[] allowedType = {"image/bmp", "image/gif", "image/jpeg", "image/png"}; boolean allowed = Arrays.asList(allowedType).contains(avatar.getContentType()); if (!allowed) { model.addAttribute("error3","图片格式仅限bmp,jpg,png,gif~"); return "editProfile"; } // 图片大小限制 if (avatar.getSize() > 3 * 1024 * 1024) { model.addAttribute("error3","图片大小限制在3M以下哦~"); return "editProfile"; } // 包含原始文件名的字符串 String filename = avatar.getOriginalFilename(); // 提取文件拓展名 String extension = filename.substring(filename.indexOf(".") +1); String dir = context.getRealPath("/upload/avatar/"); //如果目录不存在,级联创建 //.normalize()方法用于标准化路径,替换/等问题 if(!Files.exists(Paths.get(dir))) { Files.createDirectories(Paths.get(dir).normalize()); } String uuid = UUID.randomUUID().toString(); String webUrl = String.format("/upload/avatar/%s.%s",uuid,extension); String target = String.format("%s/%s.%s",dir,uuid,extension); //写入文件 Files.write(Paths.get(target).normalize(),avatar.getBytes()); //更新数据库中头像URL int uid = (int) session.getAttribute("uid"); userService.updateHeadUrl(uid,webUrl); return "redirect:profile.html"; }