使用commons-fileupload-1.3.1.jar和commons-io-2.4.jar
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 6 <display-name></display-name> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 11 <!-- springmvc前端控制器 --> 12 <servlet> 13 <servlet-name>springmvc</servlet-name> 14 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 15 <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) --> 16 <!-- 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) --> 17 18 <init-param> 19 <param-name>contextConfigLocation</param-name> 20 <param-value>classpath:springmvc.xml</param-value> 21 </init-param> 22 </servlet> 23 24 <servlet-mapping> 25 <servlet-name>springmvc</servlet-name> 26 <!-- 第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析 --> 27 <!-- 第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析 --> 28 <!-- 使用此种方式可以实现 RESTful风格的url --> 29 <!-- 第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, --> 30 <!-- 仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。 --> 31 32 <url-pattern>*.action</url-pattern> 33 </servlet-mapping> 34 35 <filter> 36 <filter-name>SpringCharacterEncodingFilter</filter-name> 37 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 38 <init-param> 39 <param-name>encoding</param-name> 40 <param-value>UTF-8</param-value> 41 </init-param> 42 </filter> 43 <filter-mapping> 44 <filter-name>SpringCharacterEncodingFilter</filter-name> 45 <url-pattern>/*</url-pattern> 46 </filter-mapping> 47 48 <welcome-file-list> 49 <welcome-file>index.html</welcome-file> 50 </welcome-file-list> 51 </web-app>
springmvc.xml
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 7 http://www.springframework.org/schema/mvc 8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-3.2.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> 15 16 17 18 <!-- 对于注解的Handler可以单个配置 实际开发中建议使用组件扫描 --> 19 <!-- <bean class="cn.demo.controller.ParamController" /> --> 20 <!-- 可以扫描controller、service、... 这里让扫描controller,指定controller的包 --> 21 <context:component-scan base-package="cn.demo.controller"></context:component-scan> 22 23 <!--spring3.1之后使用:注解映射器 --> 24 <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> 25 <!--spring3.1之后使用:注解适配器 --> 26 <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --> 27 28 <!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置 --> 29 <!-- mvc:annotation-driven默认加载很多的参数绑定方法, --> 30 <!-- 比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter --> 31 <!-- 实际开发时使用mvc:annotation-driven --> 32 33 <mvc:annotation-driven /> 34 35 36 <!-- 视图解析器 --> 37 <!-- 解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包 --> 38 <bean 39 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 40 <!-- 配置jsp路径的前缀 --> 41 <property name="prefix" value="/WEB-INF/jsp/" /> 42 <!-- 配置jsp路径的后缀 --> 43 <property name="suffix" value=".jsp" /> 44 </bean> 45 46 47 <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> 48 <bean id="multipartResolver" 49 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 50 <property name="defaultEncoding" value="UTF-8" /> 51 <!-- 指定所上传文件的总大小不能超过20000KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> 52 <property name="maxUploadSize" value="20000000" /> 53 </bean> 54 55 <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> 56 <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> 57 <bean id="exceptionResolver" 58 class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 59 <property name="exceptionMappings"> 60 <props> 61 <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 --> 62 <prop 63 key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop> 64 </props> 65 </property> 66 </bean> 67 68 </beans>
javaBean:
1 package cn.demo.po; 2 3 4 5 public class User { 6 7 8 9 public User() { 10 11 12 13 } 14 15 16 17 public User(String username, String nickname, String password, String email) { 18 super(); 19 this.username = username; 20 this.nickname = nickname; 21 this.password = password; 22 this.email = email; 23 } 24 25 26 27 private String username; 28 private String nickname; 29 private String password; 30 private String email; 31 32 33 34 public String getUsername() { 35 return username; 36 } 37 38 39 40 public void setUsername(String username) { 41 this.username = username; 42 } 43 44 45 46 public String getNickname() { 47 return nickname; 48 } 49 50 51 52 public void setNickname(String nickname) { 53 this.nickname = nickname; 54 } 55 56 57 58 public String getPassword() { 59 return password; 60 } 61 62 63 64 public void setPassword(String password) { 65 this.password = password; 66 } 67 68 69 70 public String getEmail() { 71 return email; 72 } 73 74 75 76 public void setEmail(String email) { 77 this.email = email; 78 } 79 80 81 82 }
controller:UserController
1 package cn.demo.controller; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 import javax.servlet.http.HttpServletRequest; 9 10 import org.apache.commons.io.FileUtils; 11 import org.springframework.stereotype.Controller; 12 import org.springframework.ui.Model; 13 import org.springframework.web.bind.annotation.RequestMapping; 14 import org.springframework.web.bind.annotation.RequestMethod; 15 import org.springframework.web.bind.annotation.RequestParam; 16 import org.springframework.web.multipart.MultipartFile; 17 import cn.demo.po.User; 18 19 /** 20 * SpringMVC中的文件上传 21 * 22 * @see 第一步:由于SpringMVC使用的是commons-fileupload实现,故将其组件引入项目中 23 * @see 这里用到的是commons-fileupload-1.3.1.jar和commons-io-2.4.jar 24 * @see 第二步:在springmvc.xml中配置MultipartResolver处理器。可在此加入对上传文件的属性限制 25 * @see 第三步:在Controller的方法中添加MultipartFile参数。该参数用于接收表单中file组件的内容 26 * @see 第四步:编写前台表单。注意enctype="multipart/form-data"以及<input type="file" 27 * name="****"/>不对字符编码。 在使用包含文件上传控件的表单时,必须使用该值。 28 * @author tinyseven 29 */ 30 @Controller 31 @RequestMapping("/user") 32 public class UserController { 33 private final static Map<String, User> users = new HashMap<String, User>(); 34 35 // 模拟数据源,构造初始数据 36 public UserController() { 37 users.put("AAAA", new User("AAAA", "AAAA", "133569856", "AAAA@yeah.net")); 38 users.put("BBBB", new User("BBBB", "BBBB", "154699856", "BBBB@gulong.cn")); 39 users.put("CCCC", new User("CCCC", "CCCC", "154896965", "CCCC@manhuang.cc")); 40 users.put("DDDD", new User("DDDD", "DDDD", "177654646", "DDDD@xiyouji.zh")); 41 } 42 43 @RequestMapping("/list") 44 public String list(Model model, HttpServletRequest request) { 45 model.addAttribute("users", users); 46 // request.setAttribute("users", users); 47 return "user/list"; 48 } 49 50 @RequestMapping(value = "/add", method = RequestMethod.GET) 51 public String addUser() { 52 return "user/add"; 53 } 54 55 @RequestMapping(value = "/add", method = RequestMethod.POST) 56 public String addUser(User user, @RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException { 57 // 如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解 58 // 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解 59 // 并且上传多个文件时,前台表单中的所有<input 60 // type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件 61 for (MultipartFile myfile : myfiles) { 62 if (myfile.isEmpty()) { 63 System.out.println("未上传文件"); 64 } else { 65 System.out.println("文件长度: " + myfile.getSize()); 66 System.out.println("文件类型: " + myfile.getContentType()); 67 System.out.println("文件名称: " + myfile.getName()); 68 System.out.println("文件原名: " + myfile.getOriginalFilename()); 69 System.out.println("========================================"); 70 // 如果用的是Tomcat服务器,则文件会上传到\%TOMCAT_HOME%\webapps\YourWebProject\WEB-INF\upload\文件夹中 71 String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); 72 // 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的 73 FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename())); 74 } 75 } 76 users.put(user.getUsername(), user); 77 return "redirect:/user/list.action"; 78 } 79 }
jsp页面(WEB-INF/jsp/user/add.jsp)
add.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <base href="<%=basePath%>"> <title>adduser</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <form action="<%=request.getContextPath()%>/user/add.action" method="POST" enctype="multipart/form-data"> username: <input type="text" name="username"/><br/> nickname: <input type="text" name="nickname"/><br/> password: <input type="password" name="password"/><br/> yourmail: <input type="text" name="email"/><br/> yourfile: <input type="file" name="myfiles"/><br/> yourfile: <input type="file" name="myfiles"/><br/> yourfile: <input type="file" name="myfiles"/><br/> <input type="submit" value="添加新用户"/> </form> </body> </html>
jsp页面(WEB-INF/jsp/user/list.jsp)
list.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <html> <head> <base href="<%=basePath%>"> <title>list</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <c:forEach var="user" items="${users}"> <p>${user.value.username}----${user.value.nickname}----${user.value.password}----${user.value.email}</p> <br /> </c:forEach> <br /> <a href="<%=request.getContextPath()%>/user/add.action">继续添加用户</a> </body> </html>
-END-