关于SpringMVC的文件上传

1、万变不离其宗,要实现文件的上传需要对应的JAR包:

1、commons-fileupload-1.2.2.jar

2、commons-io-2.0.1.jar

 

2、要实现SpringMVC的文件上传,需要配置一下文件:

    <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
     <bean id="multipartResolver"
         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <property name="defaultEncoding" value="UTF-8" />
         <!-- 指定所上传文件的总大小不能超过200KB。
             注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
         <property name="maxUploadSize" value="-1" />
     </bean>
 
    <!-- SpringMVC在超出上传文件限制时,会抛出异常-->
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
     <bean id="exceptionResolver"
         class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
             <props>  <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到XXX页面 -->
                <prop  key="org.springframework.web.multipart.MaxUploadSizeExceededException">
                   跳转XXX页面
                </prop>
            </props>
         </property>
   </bean>

3、上传页面

 <%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
 <%
     String path = request.getContextPath();
     String basePath = request.getScheme() + "://"
             + request.getServerName() + ":" + request.getServerPort()+ path + "/";
  %>
 
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件</title>
 </head>
<body>
    <form action="<%=basePath%>upload.do" method="post"
        enctype="multipart/form-data">
         <input type="hidden" name="tuzi" value="tuzi">
        上传文件:<input type="file" name="uploadfile">
          <input type="submit" value="上传">
     </form>
 </body>
 </html>


4、看下文件上传

  //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解   
  //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解   
  //并且上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件   

 /**
  * 文件上传处理类*/
 @Controller
 public class FileController {
 
     //单文件上传
     @RequestMapping(value = "/upload.do")
    public String queryFileData(
             @RequestParam("uploadfile") CommonsMultipartFile file,
             HttpServletRequest request) {
 
         // MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
         if (!file.isEmpty()) {
            String type = file.getOriginalFilename().substring(
                     file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
             String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
             String path = request.getSession().getServletContext()
                     .getRealPath("/upload/" + filename);// 存放位置
             File destFile = new File(path);
            try {
                 // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
 
                 // 复制临时文件到指定目录下
                 FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
             } catch (IOException e) {
                e.printStackTrace();
            }
            return "redirect:upload_ok.jsp";
        } else {
            return "redirect:upload_error.jsp";
         }
     }
 
     //多文件上传
     @RequestMapping(value = "/uploads.do")
     public String queryFileDatas(
             @RequestParam("uploadfile") CommonsMultipartFile[] files,
             HttpServletRequest request) {
         if (files != null) {
             for (int i = 0; i < files.length; i++) {
                 String type = files[i].getOriginalFilename().substring(
                         files[i].getOriginalFilename().indexOf("."));// 取文件格式后缀名
                 String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
                 String path = request.getSession().getServletContext()
                        .getRealPath("/upload/" + filename);// 存放位置
                File destFile = new File(path);
                try {     
 
              // 复制临时文件到指定目录下
               FileUtils.copyInputStreamToFile(files[i].getInputStream(),destFile);                 
              } catch (IOException e) {                  
                e.printStackTrace();                 
              }             
          }             
              return "redirect:upload_ok.jsp";         
             } else {         
           return "redirect:upload_error.jsp";       
      }    
  }  
}

    上传过程中发现上传到服务器后,取到的文件名成了乱码,解决方法是在web.xml中加一个spring的转码拦截器,转成项目的默认编码格式。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值