在实际的项目开发中,很多时候上传的文件会作为对象的属性被保存。Spring MVC 的处理也非常简单。
registerForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用户注册</title> </head> <body> <h2>用户注册</h2> <form action="register" method="post" enctype="multipart/form-data"> <table> <tr> <td>用户名:</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>请选择上传头像:</td> <td><input type="file" name="image" /></td> </tr> <tr> <td><input type="submit" value="上传" /></td> </tr> </table> </form> </body> </html> |
UploadFile.java
@RequestMapping(value="/register") public String register(HttpServletRequest request, @ModelAttribute User user, Model model) throws IllegalStateException, IOException { System.out.println(user.getUsername()); //如果文件不为空,则写入上传路径 if(!user.getImage().isEmpty()) { //上传路径 String uploadpath = request.getServletContext().getRealPath("/images/"); System.out.println("uploadpath"+uploadpath); //上传文件名 String uploadfilename = user.getImage().getOriginalFilename(); File filepath = new File(uploadpath,uploadfilename); System.out.println("filepath"+filepath); //判断路径是否存在,如果不存在就创建一个 if(!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } //将上传文件保存到一个目标文件夹当中 File dir = new File(uploadpath+File.separator+uploadfilename); System.out.println("dir"+dir); user.getImage().transferTo(dir); //将用户添加到 model model.addAttribute("user",user); return "userInfo"; }else { return "error"; } } |