在实际的项目开发中,很多时候上传的文件会作为对象的属性被保存,SpringMVC的处理也非常简单:
1.提交表单视图
<form action="/springTest/avatarUpload" enctype="multipart/form-data" method="post"> <input type="text" name="username" /> <input type="file" name="image" /> <input type="submit" value="submit" /> </form>
2.模型
public class User implements Serializable { private String username; private MultipartFile image; public User() { super(); } ...
3.控制器
@Controller public class FileUploadController { @GetMapping("/testUpload") public String testUpload( ) { return "Form8"; } @PostMapping(value="/avatarUpload") public String commit( HttpServletRequest request, @ModelAttribute User user, Model model ) throws Exception { //上传文件路径 String path = request.getServletContext().getRealPath("/images/"); //上传文件名 String filename = user.getImage().getOriginalFilename(); File filepath = new File(path,filename); //判断路径是否存在如果不存在就创建 if(!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } System.out.println(path+File.separator+filename); //将上传文件保存到目标路径当中 user.getImage().transferTo(new File(path+File.separator+filename)); model.addAttribute("user", user); return "uploadSuccess"; } }
4.显示数据视图
<h2>上传成功</h2> <h3>${user.username}</h3> <img src="images/${requestScope.user.image.originalFilename}">