MultipartFile attach
HttpServletRequest re

commons-io-2.0.jar (一定要用2.0以上的版本,否则没有copyInputStreamToFile方法)
commons-fileupload-1.2.1.jar
@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>

 

 

 

posted on 2016-09-14 10:35  Mr.He多多指教  阅读(213)  评论(0编辑  收藏  举报