这个地方讲,单文件和多文件上传,多文件上传的时候,需要指定@RequestParam说明是那个参数,不然自动注入不上。同时还需要判断文件内容是否为空的情况 ,文件上传的form需要设定enctype="multipart/form-data",而且采用post的方式提交。

配置spring-mvc-xml

需要配置multipartResolver 这个文件上传的解析器,参数的具体意思,下面也给出了解释。配置最大上传大小以及编码

<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 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-3.1.xsd">
    <mvc:default-servlet-handler/>
    <!-- 通过Annotation 来控制Controller -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <context:component-scan base-package="com.yellowcong"></context:component-scan>

    <!-- 将静态文件夹制定到某个特别的文件夹中统一处理 ** 表示的是文件夹中的子文件夹中的所有类容 其中location 需要两个 正斜杠 -->
    <mvc:resources location="/resources/" mapping="/resources/**"/>
        <!-- 配置权限拦截器 -->
        <!-- 当我们的数据访问到 amdin的时候,就会直接调用admin对象 -->
 <!-- <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/user/**"/> <mvc:mapping path="/role/**"/> <mvc:mapping path="/group/**"/> <mvc:mapping path="/attachment/**"/> <mvc:mapping path="/reply/**"/> <mvc:mapping path="/tabel/**"/> <mvc:mapping path="/image/**"/> <mvc:mapping path="/info/**"/> <mvc:mapping path="/login/stu"/> <mvc:mapping path="/admin/**"/> <bean class="com.yellowcong.interceptor.UserInterceptor"/> </mvc:interceptor> </mvc:interceptors> --> 
    <!-- 设定访问的名称 和对应的Servlet -->    
    <!-- 配置Multipart,只有设定了才能完成文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 最大文件大小,-1为无限止(-1) -->  
        <property name="maxUploadSize" value="5000000"/>
        <!-- 最大内存大小 (10240)--> 
        <property name="maxInMemorySize" value="10240"/>
        <!-- 设置编码 ,默认编码 (ISO-8859-1)-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->  
        <property name="resolveLazily" value="true"/>    
    </bean>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 3.0.5后默认加上了jstl的属性配置.这个就是默认的配置 -->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <!-- 设定前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- 设定后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置全局异常 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
            <!-- <prop key="com.yellowcong.exception.UserException">error</prop> <prop key="java.lang.RuntimeExceptio">error</prop> -->
            </props>
        </property>
    </bean>
</beans>

单文件上传

单文件上传,需要注意的是,文件的路径获取的方式,通过ServletContext对象来获取到上传的路径。

后台

package com.yellowcong.controller;

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

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.aspectj.util.FileUtil;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/** * 文件上传 * * @author yellowcong * */
@Controller
@RequestMapping(value = "/file")
public class FileDemo {
      
        

    @RequestMapping(value = "/input")
    public ModelAndView file() {
        //上传文件的路径
        String uploadPath = this.getUploadPath();
        ModelAndView view = new ModelAndView("demo/file");
        view.addObject("uploadPath", uploadPath);

        return view;
    }

    /** * 上传单个文件 * @param file * @return * @throws Exception */
    @RequestMapping(value = "/upload1",method=RequestMethod.POST)
    public ModelAndView upload1(MultipartFile file) throws Exception {
        //上传文件的路径

        //获取文件的正真名称
        String name = file.getOriginalFilename();
        String uploadPath = this.getUploadPath()+name;  

        //文件的拷贝
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(uploadPath));

        //设定文件上传
        ModelAndView view = new ModelAndView("demo/file");
        view.addObject("uploadPath", uploadPath);

        return view;
    }

    /** * 获取文件上传路径 * @return */
    public String getUploadPath() {
        // 获取到ServletRequestAttributes 里面有
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取到Request对象
        HttpServletRequest request = attrs.getRequest();
        //servlet
        ServletContext servlet = request.getServletContext();
        //获取到上传的路径
        return servlet.getRealPath("resources/upload")+File.separator;
    }

}

界面

上传文件的form表单需要配置 enctype="multipart/form-data",表明是二进制类型的。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>
<html>
<head>
<title>xx文章</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- ${user.username} 这个访问了 用户model里面的属性 -->
<h2>文件上传</h2>
<h3>上传地址:${uploadPath}</h3>

<form method="post" action="${pageContext.servletContext.contextPath}/file/upload1" enctype="multipart/form-data">
<!-- 字段需要和后台的字段对应上 -->
文件:<input type="file" name="file"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

SpringMvc之文件上传-yellowcong_mvc

多文件上传


1.多文件上传的时候,需要指定@RequestParam("file")传递过来的文件数组的参数字段名,不然设置不上,就会报错
2.需要判断MultipartFile.isEmpty() ,去掉没有上传文件的对象

后台代码

package com.yellowcong.controller;

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

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.aspectj.util.FileUtil;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/** * 文件上传 * * @author yellowcong * */
@Controller
@RequestMapping(value = "/file")
public class FileDemo {
      
        

    @RequestMapping(value = "/input")
    public ModelAndView file() {
        //上传文件的路径
        String uploadPath = this.getUploadPath();
        ModelAndView view = new ModelAndView("demo/file");
        view.addObject("uploadPath", uploadPath);

        return view;
    }

    /** * 上传多个文件的情况 * 多文件上传的时候,需要指定 @RequestParam("file") * @param file * @return * @throws Exception */
    @RequestMapping(value = "/upload2",method=RequestMethod.POST)
    public ModelAndView upload2(@RequestParam("file") MultipartFile [] file) throws Exception {
        //上传文件的路径

        for(int i=0;i<file.length;i++){
            MultipartFile partFile = file[i];
            //可能一组上传文件按钮中,只有部分上传了,有文件
            if(!partFile.isEmpty()){
                //获取文件的正真名称
                String name = partFile.getOriginalFilename();
                String uploadPath = this.getUploadPath()  + name;   

                //文件的拷贝
                FileUtils.copyInputStreamToFile(partFile.getInputStream(), new File(uploadPath));
            }
        }
        //设定文件上传
        ModelAndView view = new ModelAndView("demo/file");
        view.addObject("uploadPath", this.getUploadPath());

        return view;
    }

    /** * 获取文件上传路径 * @return */
    public String getUploadPath() {
        // 获取到ServletRequestAttributes 里面有
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取到Request对象
        HttpServletRequest request = attrs.getRequest();
        //servlet
        ServletContext servlet = request.getServletContext();
        //获取到上传的路径
        return servlet.getRealPath("resources/upload")+File.separator;
    }

}

界面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>
<html>
<head>
<title>xx文章</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- ${user.username} 这个访问了 用户model里面的属性 -->
<h2>文件上传</h2>
<h3>上传地址:${uploadPath}</h3>

<form method="post" action="${pageContext.servletContext.contextPath}/file/upload2" 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="file" name="file"/><br/>
文件:<input type="file" name="file"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

SpringMvc之文件上传-yellowcong_文件上传_02

环境搭建

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>yellowcong</groupId>
    <artifactId>day11_13</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>day11_13 Maven Webapp</name>
    <url>http://maven.apache.org</url>


    <!-- 配置国内比较快的 阿里云的Maven仓库 -->
    <repositories>
        <repository>
            <id>aliyunmaven</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <!-- 共用的配置说明,比如spring版本, 项目名称, jdk版本等 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.2.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- Spring BEGIN-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 导入Spring的orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Slf4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <!-- 配置切面 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!---aspectj 面向切向 -->
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.5</version>
        </dependency>
        <!-- Spring需要的注解 -->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Spring 的测试类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring END-->

        <!-- 配置Spring mvc -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- 文件上传 Begin-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- 文件上传 End-->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

        <!-- JSON解析 -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.11</version>
        </dependency>

        <!-- 日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>day11_13</finalName>
    </build>
</project>