@RequestMapping(value="/add",method=RequestMethod.POST) public String add(@Validated User user, BindingResult result, MultipartFile attach){ String realpath=req.getSession().getServletContext().getRealPath("/resources/upload"); File f=new File(realpath+"/"+attach.getOriginalFilename()); try { FileUtils.copyInputStreamToFile(attach.getInputStream(),f ); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } users.put(user.getUsername(), user); return "redirect:/user/users"; }
<body> <sf:form method="post" modelAttribute="user" enctype="multipart/form-data"> 用户名称:<sf:input path="username"/><sf:errors path="username"/><br/> 用户密码: <sf:input path="password"/><sf:errors path="password"/><br/> 用户昵称: <sf:input path="nickname"/> <br/> 用户邮箱: <sf:input path="email"/><sf:errors path="email"/><br/> 附件:<input type="file" name="attach"/><br/> <input type="submit" value="添加用户"/> </sf:form> </body>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
/** * Initialize the underlying {@code org.apache.commons.fileupload.servlet.ServletFileUpload} * instance. Can be overridden to use a custom subclass, e.g. for testing purposes. * @param fileItemFactory the Commons FileItemFactory to use * @return the new ServletFileUpload instance */ @Override protected FileUpload newFileUpload(FileItemFactory fileItemFactory) { return new ServletFileUpload(fileItemFactory); }
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency>
<body> <sf:form method="post" modelAttribute="user" enctype="multipart/form-data"> 用户名称:<sf:input path="username"/><sf:errors path="username"/><br/> 用户密码: <sf:input path="password"/><sf:errors path="password"/><br/> 用户昵称: <sf:input path="nickname"/> <br/> 用户邮箱: <sf:input path="email"/><sf:errors path="email"/><br/> 附件:<input type="file" name="attachs"/><br/> 附件:<input type="file" name="attachs"/><br/> 附件:<input type="file" name="attachs"/><br/> <input type="submit" value="添加用户"/> </sf:form> </body>
@RequestMapping(value = "/add", method = RequestMethod.POST) public String add(@Validated User user, BindingResult result, @RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) { for (MultipartFile attach : attachs) { String realpath = req.getSession().getServletContext() .getRealPath("/resources/upload"); File f = new File(realpath + "/" + attach.getOriginalFilename()); try { FileUtils.copyInputStreamToFile(attach.getInputStream(), f); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } users.put(user.getUsername(), user); return "redirect:/user/users"; }
/** * The name of the request parameter to bind to. */ String value() default "";)
0票
开心
0票
板砖
0票
感动
0票
有用
0票
疑问
0票
难过
0票
无聊
0票
震惊
顶
踩