Spring MVC文件上传

单文件上传

  所需依赖

  <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.2</version>
    </dependency>

  大配置文件

 

<!--文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--编码-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!--文件总大小-->
        <property name="maxInMemorySize" value="5000000"/>
        <!--单文件大小-->
        <property name="maxUploadSizePerFile" value="200000"/>
    </bean>

 

  表单

<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/file/fileone" method="post" enctype="multipart/form-data">
        <input type="file" name="file"><br>
        <input type="password" name="upwd"><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

  控制器

@RequestMapping("/fileone")
    public ModelAndView fileone(HttpSession session, MultipartFile file,String upwd) throws IOException {
        ModelAndView mv=new ModelAndView();
        System.out.println(upwd);
            //文件是否为空
            if(!file.isEmpty()){
                //获取文件名称
                String filename=file.getOriginalFilename();
                //获取文件上传路径
                String realPath = session.getServletContext().getRealPath("/WEB-INF/file");
                //创建文件对象
                File file1=new File(realPath,filename);
                //上传文件
                file.transferTo(file1);
            }
        mv.setViewName("myform");
        return mv;
    }

 

 多文件上传

  修改控制器

 @RequestMapping("/fileone1")
    public ModelAndView fileone1(HttpSession session, MultipartFile[] file,String upwd) throws IOException {
        ModelAndView mv=new ModelAndView();
        System.out.println(upwd);
        for (MultipartFile files:file){
            //是否为空
            if(!files.isEmpty()){
                //获取文件名称
                String filename=files.getOriginalFilename();
                //获取文件上传路径
                String realPath = session.getServletContext().getRealPath("/WEB-INF/file");
                //创建文件对象
                File file1=new File(realPath,filename);
                //上传文件
                files.transferTo(file1);
            }
        }
        mv.setViewName("myform");
        return mv;
    }

  修改表单

<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/file/fileone" method="post" enctype="multipart/form-data">
        <input type="file" name="file"><br>
        <input type="file" name="file"><br>
        <input type="file" name="file"><br>
        <input type="file" name="file"><br>
        <input type="password" name="upwd"><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

posted @ 2019-11-11 15:27  梅川酷子灬  阅读(106)  评论(0编辑  收藏  举报