代码改变世界

Spring mvc上传多文件

2015-12-04 09:10  小兵故事  阅读(301)  评论(0编辑  收藏  举报

 

jsp页面

<form action="${pageContext.request.contextPath }/user/upload" method="post" enctype="multipart/form-data">
   	attach 1:<input type="file" name="attachs" /><br/>
   	attach 2:<input type="file" name="attachs"/><br/>
   	<button type="submit">提交</button>
</form>

 

controller.java 接收数据(代码如下)

@RequestMapping(value="/upload",method=RequestMethod.POST )
    public String upload(@RequestParam("attachs") MultipartFile[] attachs,HttpServletRequest req){
        String realPath=req.getSession().getServletContext().getRealPath("/resources/upload");//保存的路径
        System.out.println(attachs.length);
        System.out.println(realPath);
        for(MultipartFile attach:attachs){
            System.out.println(attach);
            if(!attach.isEmpty()){
                File file=new File(realPath+"/"+attach.getOriginalFilename());
                try {
            //底层数据io传输 attach.transferTo(file); }
catch (IllegalStateException | IOException e) { e.printStackTrace(); } } } return "welcome"; }


dispatcherServlet-servlet.xml  代码:

<!-- 配置MultipartResolver,用于上传文件,使用Spring的CommonsMultiparResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
            <property name="defaultEncoding" value="UTF-8"/>
    </bean>