首页 > 代码库 > spring mvc 文件上传

spring mvc 文件上传

                                                                          spring mvc 文件上传  

一、单文件上传

配置步骤:

步骤一、在配置文件中配置包扫描器(暂且这样配,会出问题,我们下面说解决方案)

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
 
     <!--让spring扫描包下所有的类,让标注spring注解的类生效  -->
     <context:component-scan base-package="cn.hmy.controller"/>
     
</beans>

 

步骤二,定制我们的文件上传jsp页面

<%@ page language="java" import="java.util.*" 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">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>文件上传</title>
  </head>
  
  <body>
     <form action="${pageContext.request.contextPath }/list.do" method="post" enctype="multipart/form-data">
       <h1>文件上传</h1>
                 文件:<input type="file" name="fileUpLoad"/></br>
        <input type="submit" value="上传"/>         
    </form>
  </body>
</html>

步骤三、书写我们的处理器代码

package cn.hmy.controller;



import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.hmy.pojo.UserInfo;

@Controller
public class MyController{
       //处理器方法
     @RequestMapping(value="http://www.mamicode.com/list.do")    
     public void doFirst(MultipartFile fileUpLoad,HttpSession session) throws Exception{
         //1.获取文件名称
         String filename = fileUpLoad.getOriginalFilename();
         //2.获取文件的前半部分路径
         String realPath = session.getServletContext().getRealPath("/images");
         //3.拼接成完整的路径
         File file=new File(realPath,filename);
         //4.保存文件
         fileUpLoad.transferTo(file); 
     }        
}

此时我们启动服务器,进行代码上传,会报如下错误

 

技术分享

解决方案:更改我们的spring-servlet.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
 
     <!--让spring扫描包下所有的类,让标注spring注解的类生效  -->
     <context:component-scan base-package="cn.hmy.controller"/>
<!--配置复杂类型表达解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> </beans>

启动发现还是会报上述错误 

解决方案:配置注解驱动

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
 
     <!--让spring扫描包下所有的类,让标注spring注解的类生效  -->
     <context:component-scan base-package="cn.hmy.controller"/>
<!--配置复杂类型表达解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
<!--配置注解驱动-->
<mvc:annotation-driven/> </beans>

如果在上述配置文件中缺少复杂类型解析器,会报如下错误

技术分享

 

 

在解决了以上错误后,我们会发现如果我们上传的文件中含有中文   会出现乱码现象

解决乱码

解决方案我们暂且提供以下两种方式

方案一、技术分享

方案二、在web.xml中配置

<filter>
    <filter-name>characterEncoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

 

如何控制文件上传大小

在spring-servlet.xml中配置如下

maxUploadSize为上传的总文件的大小 5M
maxInMemorySize为上传的单个文件的大小 1M
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <property name="defaultEncoding" value="utf-8"></property>
       <property name="maxUploadSize" value="5000000"></property>
       <property name="maxInMemorySize" value="1000000"></property>
     </bean>

如果超出所限制的大小  会报如下错误

技术分享

 

 

控制文件上传的类型(通过后缀名进行控制)在处理器中进行判定

例如 只允许上传.jpg   .png   .gif为后缀的文件

package cn.hmy.controller;



import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.hmy.pojo.UserInfo;

@Controller
public class MyController{
       //处理器方法
     @RequestMapping(value="http://www.mamicode.com/list.do")    
     public String doFirst(MultipartFile fileUpLoad,HttpSession session) throws Exception{
         
         
        //1.获取文件名称
         String filename = fileUpLoad.getOriginalFilename();
         //限定文件上传的类型
         if(filename.endsWith("jpg")||filename.endsWith("png")||filename.endsWith("gif")){
            //2.获取文件的前半部分路径
             String realPath = session.getServletContext().getRealPath("/images");
             //3.拼接成完整的路径
             File file=new File(realPath,filename);
             //4.保存文件
             fileUpLoad.transferTo(file); 
         }else{
             System.out.println("不支持上传文件的类型");
         }
         
         return "/list.jsp";
         
     }        
}

 

 

 

如何判断用户没用选上传文件

 

 

多文件上传

步骤一、

spring-servlet.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
 
     <!--让spring扫描包下所有的类,让标注spring注解的类生效  -->
     <context:component-scan base-package="cn.hmy.controller"/>
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <property name="defaultEncoding" value="http://www.mamicode.com/utf-8"></property>
       <property name="maxUploadSize" value="http://www.mamicode.com/5000000"></property>
       <property name="maxInMemorySize" value="http://www.mamicode.com/1000000"></property>
     </bean>
     <mvc:annotation-driven/>
</beans>

 

步骤二、准备多文件上传的jsp页面

<%@ page language="java" import="java.util.*" 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">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>文件上传</title>
  </head>
  
  <body>
     <form action="${pageContext.request.contextPath }/list.do" method="post" enctype="multipart/form-data">
       <h1>文件上传</h1>
                 文件1:<input type="file" name="fileUpLoad"/></br>
                 文件2:<input type="file" name="fileUpLoad"/></br>
                 文件3:<input type="file" name="fileUpLoad"/></br>
       <input type="submit" value="上传"/>         
    </form>
  </body>
</html>

步骤三、编写处理器的代码

 //多文件上传
     @RequestMapping(value="http://www.mamicode.com/list.do")    
     public String doFirst2(@RequestParam MultipartFile[] fileUpLoad,HttpSession session) throws Exception{
         for (MultipartFile item : fileUpLoad) {
             //1.获取文件名称
             String filename = item.getOriginalFilename();
             //限定文件上传的类型
             if(filename.endsWith("jpg")||filename.endsWith("png")||filename.endsWith("gif")){
                //2.获取文件的前半部分路径
                 String realPath = session.getServletContext().getRealPath("/images");
                 //3.拼接成完整的路径
                 File file=new File(realPath,filename);
                 //4.保存文件
                 item.transferTo(file); 
             }else{
                 System.out.println("不支持上传文件的类型");
             }
        }
        
         
         return "/list.jsp";
         }

注意:在处理器方法中一定要对参数进行校对使用注解@RequestParam校正参数

丢到  会报错

技术分享

即可实现多文件上传

 

spring mvc 文件上传