上传文件
SpringBoot+ThymeLeaf+JPA
前台
表单的enctype="multipart/form-data" 不要忘记设置
<input id="image" type="file" name="image" onchange="showPhoto(this)">
后台
SpringMVC使用MultipartFile来接收前台传入的文件
//常量建议配置在properties配置文件中,这里先这样凑合用. final static String LOCAL_FILE_LOCATION = "C:/project_image/test/"; @RequestMapping("/editUser") @ResponseBody public String editUser(User user, MultipartFile image, Model m, HttpSession session) throws IOException{ //文件的字节数组和原文件名 byte[] bytes = image.getBytes(); String originalFilename = image.getOriginalFilename(); //截取文件名和后缀 int pointIndex = originalFilename.lastIndexOf("."); String firstFileName = originalFilename.substring(0, pointIndex); String lastFileName = originalFilename.substring(pointIndex); //用随机数字和日期拼接新文件名 String timeString = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); StringBuffer newNameSB = new StringBuffer(UUID.randomUUID().toString()).append(timeString); String newFileName = newNameSB.toString(); //把文件的字节数组保存到本地 FileOutputStream fileOutputStream = new FileOutputStream(LOCAL_FILE_LOCATION + newFileName); fileOutputStream.write(bytes); fileOutputStream.flush(); fileOutputStream.close(); //给User注值 User sessionUser = (User) session.getAttribute("user"); user.setImageName(newFileName); user.setImageSuffix(lastFileName); user.setId(sessionUser.getId()); //持久化 User res = us.saveEdit(user); if(res == null){ m.addAttribute("info", "修改失败!"); }else { //持久化后更新session的信息 session.setAttribute("user",res ); m.addAttribute("info", "修改成功!"); } return "editUser"; }
f