6.springMVC中文件的上传

视频教程地址:http://edu.51cto.com/sd/2cfc2

在讲springMVC中文件的上传的时候主要以讲图片为主,这里你如果要在jsp页面显示你上传的图片的时候需要注意一点:

  就是在springMVC中,静态的资源文件是无法直接访问的,需要在springMVC的配置文件中配置

  所谓的静态资源文件主要指:js、css,img......等等

  配置如下:底下的配置意思是代表,WebRoot底下的某个文件夹底下的所有文件,location表示位置,/**表示该目录底下的所有文件

<mvc:resources location="/js/" mapping="/js/**"/>

  在springMVC中文件的上传比较简单,springMVC提供了一个转存文件的功能,使用起来相对简单,总结步骤如下:

    单文件上传:

    配置文件:

     1.添加文件上传的解析器  

<!--文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>5242800</value> </property> <property name="defaultEncoding"> <value>UTF-8</value> </property> </bean>

    页面:

      2.修改form表单中enctype这个属性的内容

<form action="photos" method="post" enctype="multipart/form-data">

        3.设置 input  type="file"

<input type="file" name="file" ></br>

    控制器:

      4.判断是否有文件传来

      5.设置文件路径

      6.转存文件    

    @RequestMapping(value = "/photo")
    public String photo(HttpServletRequest request, 
            @RequestParam("file")MultipartFile file) throws IllegalStateException, IOException {
        // 判断图片是否为空
        if (file != null) {
            // 设置图片路径(表示WebRoot底下的upload目录)
            String filepath = request.getSession().getServletContext()
                    .getRealPath("/")
                    + "/upload/" + file.getOriginalFilename();
            // 转存图片
            file.transferTo(new File(filepath));
        }
        return "hello";
}

页面怎么显示你只要取文件名就ok了。

  批量文件上传:思路大概是这样,页面传多个文件过来,后台进行遍历文件,然后调用单文件上传的方法,一个个文件转存就ok,我直接贴代码

  注意点:

    1.你页面的name属性必须一致

 <form action="photos" method="post" enctype="multipart/form-data">
   图片:  <input type="file" name="files" ></br>
   <input type="file" name="files" ></br>
   <input type="file" name="files" ></br>
   <input type="file" name="files" ></br>
    <input type="submit" value="提交"></br>
    </form>

    2.在你后台的控制器的方法上加上@RequestParam("files")这个注解,如果不报错可以不加,报错的话,加上就可以解决

     批量上传的时候,在你的单文件上传的参数上也加上这个注解。

@RequestMapping(value = "/photos")
    public String photos(HttpServletRequest request,
            @RequestParam("files")MultipartFile []files) throws IllegalStateException, IOException {
         //判定是否有文件
    
if(files.length>0){ for (int i = 0; i < files.length; i++) {
          //遍历文件 MultipartFile file
= files[i];
          //调用单文件上传的方法
          this.photo(request, file); } } return null; }

  

原文地址:https://www.cnblogs.com/huaixiaoz/p/5780622.html