首页 技术 正文
技术 2022年11月17日
0 收藏 402 点赞 2,228 浏览 9521 个字

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

项目目录树:

SpringMVC学习笔记八:文件上传及多个文件上传

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学习笔记八:文件上传及多个文件上传

SpringMVC学习笔记八:文件上传及多个文件上传

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

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

SpringMVC学习笔记八:文件上传及多个文件上传

注意点:必须在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 %>" rel="external nofollow" >
<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>

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,405
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898