MultipartFile attach
HttpServletRequest re
@RequestMapping(value="/add",method=RequestMethod.POST) public String userAdd(@Validated User user,BindingResult br,MultipartFile attach,HttpServletRequest re) throws IOException{//一定要紧跟validate写,验证结果类,中间如果有其他参数,就会报错 if(br.hasErrors()){ return "user/add"; } if(!attach.isEmpty()){ String realPath = re.getSession().getServletContext().getRealPath("/Resources/upload"); System.out.println(realPath); File f = new File(realPath+"/"+attach.getOriginalFilename()); FileUtils.copyInputStreamToFile(attach.getInputStream(), f); } users.put(user.getNickname(), user); //客户端跳转 return "redirect:/user/users"; }
<!-- 设置multipartResolver才能完成文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5000000"></property> </bean>
<sf:form method="post" modelAttribute="user" enctype="multipart/form-data"> <%-- <sf:textarea path=""/> --%> Username:<sf:input path="username"/> <sf:errors path="username"></sf:errors></br> Password:<sf:password path="password"/> <sf:errors path="password"></sf:errors></br> Nickname:<sf:input path="nickname"/> <!-- 对于没有path的,必须要在参数里面传,才能接收 --> FileUpload:<input type="file" name="attach"/> <input type="submit" value="添加用户" /> </sf:form>
时间: 2024-10-06 03:44:21