一、配置文件 web.xml <?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/200 ...
一、配置文件
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>SpringCharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SpringCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/user/add.jsp</welcome-file>
</welcome-file-list>
</web-app>
SpringMVC的配置文件upload-servlet.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/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.jadyer"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- SpringMVC上傳文件時,需要配置MultipartResolver處理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- 指定所上傳文件的總大小不能超過200KB。註意maxUploadSize屬性的限制不是針對單個文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="200000"/>
</bean>
<!-- SpringMVC在超出上傳文件限制時,會拋出org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 該異常是SpringMVC在檢查上傳的文件信息時拋出來的,而且此時還沒有進入到Controller方法中 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException異常時,自動跳轉到/WEB-INF/jsp/error_fileupload.jsp頁面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
</props>
</property>
</bean>
</beans>
二、後端代碼如下:
實體類User.java
package com.jadyer.model;
public class User {
private String username;
private String nickname;
private String password;
private String email;
/*==四個屬性的getter()、setter()略==*/
public User() {}
public User(String username, String nickname, String password, String email) {
this.username = username;
this.nickname = nickname;
this.password = password;
this.email = email;
}
}
核心的UserController.java
package com.jadyer.controller;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.multipart.MultipartFile;
import com.jadyer.model.User;
/**
* SpringMVC中的文件上傳
* @see 第一步:由於SpringMVC使用的是commons-fileupload實現,故將其組件引入項目中
* @see 這裡用到的是commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar
* @see 第二步:在####-servlet.xml中配置MultipartResolver處理器。可在此加入對上傳文件的屬性限制
* @see 第三步:在Controller的方法中添加MultipartFile參數。該參數用於接收表單中file組件的內容
* @see 第四步:編寫前臺表單。註意enctype="multipart/form-data"以及<input type="file" name="****"/>
*/
@Controller
@RequestMapping("/user")
public class UserController {
private final static Map<String,User> users = new HashMap<String,User>();
//模擬數據源,構造初始數據
public UserController(){
users.put("張起靈", new User("張起靈", "悶油瓶", "02200059", "[email protected]"));
users.put("李尋歡", new User("李尋歡", "李探花", "08866659", "[email protected]"));
users.put("拓拔野", new User("拓拔野", "搜神記", "05577759", "[email protected]"));
users.put("孫悟空", new User("孫悟空", "美猴王", "03311159", "[email protected]"));
}
@RequestMapping("/list")
public String list(Model model){
model.addAttribute("users", users);
return "user/list";
}
@RequestMapping(value="/add", method=RequestMethod.GET)
public String addUser(){
return "user/add";
}
@RequestMapping(value="/add", method=RequestMethod.POST)
public String addUser(User user, @RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException{
//如果只是上傳一個文件,則只需要MultipartFile類型接收文件即可,而且無需顯式指定@RequestParam註解
//如果想上傳多個文件,那麼這裡就要用MultipartFile[]類型來接收文件,並且還要指定@RequestParam註解
//並且上傳多個文件時,前臺表單中的所有<input type="file"/>的name都應該是myfiles,否則參數里的myfiles無法獲取到所有上傳的文件
for(MultipartFile myfile : myfiles){
if(myfile.isEmpty()){
System.out.println("文件未上傳");
}else{
System.out.println("文件長度: " + myfile.getSize());
System.out.println("文件類型: " + myfile.getContentType());
System.out.println("文件名稱: " + myfile.getName());
System.out.println("文件原名: " + myfile.getOriginalFilename());
System.out.println("========================================");
//如果用的是Tomcat伺服器,則文件會上傳到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夾中
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
//這裡不必處理IO流關閉的問題,因為FileUtils.copyInputStreamToFile()方法內部會自動把用到的IO流關掉,我是看它的源碼才知道的
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
}
}
users.put(user.getUsername(), user);
return "redirect:/user/list";
}
}
三、前端代碼
上傳的表單頁面//WEB-INF//jsp//user//add.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<form action="<%=request.getContextPath()%>/user/add" 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>
下麵是上傳成功後列印用戶信息的頁面//WEB-INF//jsp//user//list.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach items="${users}" var="user">
${user.value.username}----${user.value.nickname}----${user.value.password}----${user.value.email}
<a href="<%=request.getContextPath()%>/user/${user.value.username}">查看</a>
<a href="<%=request.getContextPath()%>/user/${user.value.username}/update">編輯</a>
<a href="<%=request.getContextPath()%>/user/${user.value.username}/delete">刪除</a>
<br/>
</c:forEach>
<br/>
<a href="<%=request.getContextPath()%>/user/add">繼續添加用戶</a>
下麵是上傳文件內容過大時的提示頁面//WEB-INF//jsp//error_fileupload.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<h1>文件過大,請重新選擇</h1>