SpringMVC实现文件上传需要加入jar包,commons-fileupload-1.3.1.jar,commons-io-2.2.jar

项目目录树:

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>springMVC</groupId>
<artifactId>springmvc01</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springmvc01 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.3</version>
</dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.3</version>
</dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.3</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency> </dependencies>
<build>
<finalName>springmvc01</finalName>
</build>
</project>

web.xml配置

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <!-- 注册字符集Filter -->
<filter>
<filter-name>characterEncodingFiter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 注册springMVC中央调度器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> </web-app>

spring-mvc.xml SpringMVC的配置文件

<?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-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 扫描注解 -->
<context:component-scan base-package="com.orange.controller" /> <!-- 注册multipart解析器,这个id是固定的,由DispatcherServlet直接调用 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="GBK" />
<property name="maxUploadSize" value="102400"></property>
<!-- 改属性延迟解析,当进入Controller时开始解析,这样就可以捕获到异常,否则由SpringMVC抛出异常时无法捕获 -->
<property name="resolveLazily" value="true"></property>
</bean>
</beans>

控制器UploadController.java

package com.orange.controller;

import java.io.File;
import java.io.IOException; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView; @Controller
@RequestMapping(value="/upload")
public class UploadController { @RequestMapping(value="/upload")
public String doUpload(@RequestParam MultipartFile photo, HttpSession session) throws Exception{ if(!photo.isEmpty()){
String path = session.getServletContext().getRealPath("/upload");
String fileName = photo.getOriginalFilename();
if(fileName.endsWith(".jpg") || fileName.endsWith(".png")){
File file = new File(path, fileName); photo.transferTo(file);
} else {
return "/fail.jsp";
}
} return "/success.jsp";
}
//拦截异常,当上传文件的大小超过1024 1M时会抛出MaxUploadSizeExceededException
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView exceptionUpload(Exception ex) throws Exception{
ModelAndView mav = new ModelAndView();
mav.addObject("ex", ex);
mav.setViewName("/fail.jsp");
return mav;
}
}

需要在webapp下创建目录upload

测试:上传图片

修改SpringMVC的配置文件spring-mvc.xml,把上传限制为1024,这时上传的文件大于1024,或抛出异常

<property name="maxUploadSize" value="1024"></property>

注意点:必须在spring-mvc.xml注册umltipart解析器时,配置<property name="resolveLazily" value="true"></property>,否则无法使用异常处理器拦截异常,应该不配置时,

是由springmvc框架抛出异常,无法拦截,但配置后,会延迟解析,进入Controller时才解析抛出异常,这时注册异常处理器就可以拦截到

如果上传多个文件,修改Controller中的配置为

package com.orange.controller;

import java.io.File;
import java.io.IOException; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView; @Controller
@RequestMapping(value="/upload")
public class UploadController { @RequestMapping(value="/upload")
public String doUpload(@RequestParam MultipartFile[] photo, HttpSession session) throws Exception{ for(int i=0; i<photo.length; i++){
if(!photo[i].isEmpty()){
String path = session.getServletContext().getRealPath("/upload");
String fileName = photo[i].getOriginalFilename();
if(fileName.endsWith(".jpg") || fileName.endsWith(".png")){
File file = new File(path, fileName); photo[i].transferTo(file);
} else {
return "/fail.jsp";
}
}
} return "/success.jsp";
} @ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView exceptionUpload(Exception ex) throws Exception{
ModelAndView mav = new ModelAndView();
mav.addObject("ex", ex);
mav.setViewName("/fail.jsp");
return mav;
}
}

修改上传upload.jsp

<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
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=GBK">
<base href="<%=basePath %>">
<title>Default Page</title>
</head>
<body> <div>
<form action="upload/upload" enctype="multipart/form-data" method="post">
照片:<input type="file" name="photo"><br>
照片:<input type="file" name="photo"><br>
照片:<input type="file" name="photo"><br>
照片:<input type="file" name="photo"><br>
照片:<input type="file" name="photo"><br>
<input type="submit" value="上传">
</form>
</div> </body>
</html>

修改spring-mvx.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: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-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 扫描注解 -->
<context:component-scan base-package="com.orange.controller" /> <!-- 注册multipart解析器,这个id是固定的,由DispatcherServlet直接调用 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="GBK" />
<!-- 上传的文件总大小 -->
<property name="maxUploadSize" value="1024000000"></property>
<!-- 每个上传的文件的大小 -->
<property name="maxUploadSizePerFile" value="102400"></property>
<!-- 改属性延迟解析,当进入Controller时开始解析,这样就可以捕获到异常,否则由SpringMVC抛出异常时无法捕获 -->
<property name="resolveLazily" value="true"></property>
</bean>
</beans>

多文件上传这里就不在演示了

SpringMVC学习笔记八:文件上传及多个文件上传的更多相关文章

  1. SpringMVC学习笔记八:文件上传下载(转)

    转自:http://www.cnblogs.com/WJ-163/p/6269409.html 一.关键步骤 ①引入核心JAR文件 SpringMVC实现文件上传,需要再添加两个jar包.一个是文件上 ...

  2. SpringMVC:学习笔记(8)——文件上传

    SpringMVC--文件上传 说明: 文件上传的途径 文件上传主要有两种方式: 1.使用Apache Commons FileUpload元件. 2.利用Servlet3.0及其更高版本的内置支持. ...

  3. SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传

    SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传 配置CKEDITOR 精简文件 解压之后可以看到ckeditor/lang下面有很多语言的js,如果不需要那么多种语言的,可 ...

  4. 史上最全的SpringMVC学习笔记

    SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...

  5. springmvc学习笔记(简介及使用)

    springmvc学习笔记(简介及使用) 工作之余, 回顾了一下springmvc的相关内容, 这次也为后面复习什么的做个标记, 也希望能与大家交流学习, 通过回帖留言等方式表达自己的观点或学习心得. ...

  6. SpringMVC学习笔记之二(SpringMVC高级参数绑定)

    一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...

  7. 【opencv学习笔记八】创建TrackBar轨迹条

    createTrackbar这个函数我们以后会经常用到,它创建一个可以调整数值的轨迹条,并将轨迹条附加到指定的窗口上,使用起来很方便.首先大家要记住,它往往会和一个回调函数配合起来使用.先看下他的函数 ...

  8. springmvc学习笔记(常用注解)

    springmvc学习笔记(常用注解) 1. @Controller @Controller注解用于表示一个类的实例是页面控制器(后面都将称为控制器). 使用@Controller注解定义的控制器有如 ...

  9. springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定

    springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定 标签: springmvc springmvc学习笔记13-springmvc注解开发之集合类型參数绑定 数组绑定 需 ...

随机推荐

  1. iphone对fixed模态框支持不太好,弹出窗口中滚动点击穿透的bug

    iphone对fixed展现层中存在滚动内容支持非常不好, 尤其是背景页面产生滚动以后,输入控件就找不到了, 取消冒泡也不行,最后是这么解决的,可以参考 <style> .modeldiv ...

  2. subprocess.Popen stdout重定向内容实时获取

    python 打开一个新进程执行系统命令, test 执行完才能获取返回, test1 实时获取返回结果 import subprocess def test(cmd): p = subprocess ...

  3. 17.3.12--smtplib模块发送邮件__抄送,安装与下载

    1-----在日常编程中,经常会用到处理email,发送,接收,抄送,下载邮件内容等操作,这时候就需要用Python的smtplib模块 smtplib与Email服务器(server)相互通信来传送 ...

  4. 17.3.12--urllib2模块

    1---urllib2是非常强大的Python网络资源访问模块,它的功能和urllib模块相似 python标准库中的urllib2模块可以说是urlib模块的一个升级的复杂版,不需要另外下载, 比如 ...

  5. JAVA--Mybatis-Spring-SpringMVC框架整合

    ------Mybatis-Spring-SpringMVC框架整合示例----- mybatis SQL映射文件 <?xml version="1.0" encoding= ...

  6. 编程基础-servlet1

    1.Servelet是什么 sevlet是Server与Applet 的缩写,即服务端小程序.Sun公司提供的开发动态web资源的技术. servelet本质是java类,但遵循Servlet规范,没 ...

  7. POJ 1845 Sumdiv [素数分解 快速幂取模 二分求和等比数列]

    传送门:http://poj.org/problem?id=1845 大致题意: 求A^B的所有约数(即因子)之和,并对其取模 9901再输出. 解题基础: 1) 整数的唯一分解定理: 任意正整数都有 ...

  8. 吴裕雄--天生自然TensorFlow高层封装:Keras-CNN

    # 1. 数据预处理 import keras from keras import backend as K from keras.datasets import mnist from keras.m ...

  9. Linux介绍,基本命令

  10. mysql之存储过程(二)

    1.批量根据复杂的SQL查询结果插入到新表 DELIMITER && CREATE PROCEDURE settlePADTEST() begin        DECLARE c_s ...