springmvc 文件上传

 

单个 文件上传 

给你jsp页面 

 

 

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<form action="/first" method="post" enctype="multipart/form-data">
    文件1   <input type="file" name="upload"/>
    <input type="submit"/>
</form>
</body>
</html>

 

注意 是 post  以及enctype的写法 

xml有一个  bean 

  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="20971520"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

 

    id不能乱起,这是规定的,  class :  CommonsMultipartResolver

    max 文件上传的最大容量  单位为字节 byte  1024byte=1kb  

   defaultEncoding 为解决文件上传的文件名的乱码 

   

    @RequestMapping("/first")
    public String first(MultipartFile upload, HttpSession session){
        System.out.println("文件上传");
        String originalFilename = upload.getOriginalFilename();
        String realPath = session.getServletContext().getRealPath("/upload");
        File file=new File(realPath,originalFilename);
        try {
            upload.transferTo(file);
            return "ax";
        } catch (IOException e) {
            e.printStackTrace();
        }


        return  "fil";

    }

   控制器       upload.getSize()>0 这个可以检查是否文件上传,

   单个,你的项目下,要有一个 upload文件夹    

originalFilename.endwiith("jsp")  判断文件上传的类型   

  现在给你们多文件上传 

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<form action="/first" method="post" enctype="multipart/form-data">
    文件1   <input type="file" name="upload"/>
    文件2   <input type="file" name="upload"/>
    文件3   <input type="file" name="upload"/>
    <input type="submit"/>
</form>
</body>
</html>
  @RequestMapping("/first")
    public String first(@RequestParam  MultipartFile[] upload, HttpSession session){
        System.out.println("文件上传");
        for (MultipartFile uu:upload) {
            String originalFilename = uu.getOriginalFilename();
            String realPath = session.getServletContext().getRealPath("/upload");
            File file = new File(realPath, originalFilename);
            try {
                uu.transferTo(file);
             
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        
        return  "fil";

    }

必须进行 @RequestParam    

 

posted on 2018-04-02 15:34  LWJDD  阅读(107)  评论(0编辑  收藏  举报

导航