1:导入commons-fileupload-1.3.jar,commons-io-1.3.2.jar 这两个jar包。
2:在Spring.xml文件中添加Bean,如下
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><bean id="multipartResolver"</span>
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- set the max upload size 5MB -->
<property name="maxUploadSize" value="5242880" /> <!--In KB -->
<property name="defaultEncoding" value="UTF-8" />
</bean>
此处限制文件最大为5MB。
3:配置web.xml , 定义mvc-dispatcher处理请求。
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/cfg/spring/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
package com.order.control;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/files")
public class FileUploadController {
@RequestMapping("/showUpload")
public ModelAndView showUpload(HttpServletRequest request){
return new ModelAndView("commons/fileupload");
}
@RequestMapping("/upload")
public ModelAndView upload(HttpServletRequest request){
try {
// 转型为MultipartHttpRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 根据前台的name名称得到上传的文件
MultipartFile file = multipartRequest.getFile("file");
// 获得文件名:
String realFileName = file.getOriginalFilename();
// 获取路径
String separator = System.getProperty("file.separator");
String ctxPath = request.getSession().getServletContext()
.getRealPath("/") + separator + "files"+separator;
// 创建文件夹
File dirPath = new File(ctxPath);
// 文件夹不存在 新建文件夹
if (!dirPath.exists()) {
dirPath.mkdir();
}
// 创建文件
File uploadFile = new File(ctxPath + realFileName);
FileCopyUtils.copy(file.getBytes(), uploadFile);
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView("success");
}
}
5.前台JSP页面
<%@ page pageEncoding="utf-8"%>
<%@ include file="../commons/commons.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>上传文件</title>
</head>
<body>
<form action="${ROOT_PATH}/files/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" /> <input type="submit" value="Submit" /></form>
</body>
注意 form 必需设置method=“post”,enctype="multipart/form-data"
否则会报org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest