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. redis基本指令

    1.键值相关命令       keys * 取出当前所有的key       exists name 查看n是否有name这个key       del name 删除key name       e ...

  2. 打水滴(BFS)

    在一个n行m列的网格中,某些位置存在一些水滴.嘟嘟进行q次打水滴操作,每次嘟嘟在某一个网格当中添加一个水滴,当某一网格中的水滴数量超过L时,该网格中的水滴变为四个水滴,并分别向上下左右四个方向飞出,每 ...

  3. 洛谷 P2622 关灯问题II【状压DP】

    传送门:https://www.luogu.org/problemnew/show/P2622 题面: 题目描述 现有n盏灯,以及m个按钮.每个按钮可以同时控制这n盏灯--按下了第i个按钮,对于所有的 ...

  4. [Algo] 397. Right Shift By N Characters

    Right shift a given string by n characters. Assumptions The given string is not null. n >= 0. Exa ...

  5. msgfmt - 翻译汉化

    说明 目前大部分自由软件实现国际化使用的是gettext. 国际化就是让程序可以使用多国语言来显示程序里的字符串. 程序里一般都有很多字符串,菜单名也好,错误信息也好,都是字符串.假设字符串为stri ...

  6. 01 语言基础+高级:1-7 异常与多线程_day05 【异常、线程】

    day05 [异常.线程] 主要内容 异常.线程 教学目标 能够辨别程序中异常和错误的区别 说出异常的分类 说出虚拟机处理异常的方式 列举出常见的三个运行期异常 能够使用try...catch关键字处 ...

  7. [ZJOI2019]麻将(DP+有限状态自动机)

    首先只需要考虑每种牌出现的张数即可,然后判断一副牌是否能胡,可以DP一下,令f[i][j][k][0/1]表示到了第i位,用j次i-1,i,i+1和k次i,i+1,i+2,是否出现对子然后最大的面子数 ...

  8. Python数据分析与展示第0&1周学习笔记(北理工 嵩天)

    一前奏 1..Python语言开发工具选择 IDLE:自带默认常用入门级 PyCharm:简单.集成度高 Anaconda:awesome IDE较为简单,不做详细记录. 二.表示 1.numpy库入 ...

  9. 利用face_recognition,dlib与OpenCV调用摄像头进行人脸识别

    用已经搭建好 face_recognition,dlib 环境来进行人脸识别 未搭建好环境请参考:https://www.cnblogs.com/guihua-pingting/p/12201077. ...

  10. mac环境下创建bash_profile文件并写入内容 更改php环境变量

    1. 启动终端Terminal 2. 进入当前用户的home目录 输入cd ~ 3. 创建.bash_profile 输入touch .bash_profile 4. 编辑.bash_profile文 ...