spring mvc的文件上传模块是可插拔的,默认没有启用,只要在 spring mvc 容器中实例化 MultipartResolver 接口的实现类即可,spring mvc 为我们提供了整合了 commons-fileupload 的 CommonsMultipartResolver 解析器,只需实例化该类即可。

配置文件

<?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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

<mvc:annotation-driven/>
<context:component-scan base-package="com.troy"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="commonsMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 最大文件大小,单位字节 -->
<property name="maxUploadSize" value="100000"/>
</bean>
</beans>

解析器id必须是multipartResolver,否则spring将在上传超过3m文件时会报错!!!

jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
</head>
<body>
<form action="file/upLoad" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>

java后台

@RequestMapping(value="/file")
@Controller
public class FileController {

@RequestMapping(value="/init")
public String init(){

return "file";
}

@RequestMapping(value="/upLoad")
@ResponseBody
public void upLoad(HttpServletRequest request) throws Exception{

//创建一个多分解的容器
CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getSession().getServletContext());
//设置编码
cmr.setDefaultEncoding("utf-8");
//判断是否有文件上传
if(cmr.isMultipart(request)){
//将request转换成多分解请求
MultipartHttpServletRequest mhs = cmr.resolveMultipart(request);
//根据input中存在的name来获取是否存在上传文件
MultipartFile mf = mhs.getFile("file");#这里可以用getFiles("file")的方式来处理多个文件。返回的是一个list.然后一个一个处理就可以了
//创建文件保存名
File file = new File(mf.getOriginalFilename());
//上传文件
mf.transferTo(file);
}
}
}

使用MultipartFile类的相关API完成文件上传

@Controller
public class FileUploadController {
private static final String UPLOAD_DIR = "/srv/www/upload/";
private static final long MAX_FILE_SISE = 1000000;

@RequestMapping("/upload")
public void uploadFile(@RequestParam("file") MultipartFile file) {
if(!file.isEmpty()) {
//获取文件类型
String contentType = file.getContentType();
if(!contentType.equals("")) {
//可以对文件类型进行检查
}
//获取input域的name属性
String name = file.getName();
//获取文件名,带扩展名
String originFileName = file.getOriginalFilename();
//获取文件扩展名
String extension = originFileName.substring(originFileName.lastIndexOf("."));
System.out.println(extension);
//获取文件大小,单位字节
long site = file.getSize();
if(site > MAX_FILE_SISE) {
//可以对文件大小进行检查
}
//构造文件上传后的文件绝对路径,这里取系统时间戳+文件名作为文件名
//不推荐这么写,这里只是举例子,这么写会有并发问题
//应该采用一定的算法生成独一无二的的文件名
String fileName = UPLOAD_DIR + String.valueOf(System.currentTimeMillis()) + extension;
try {
file.transferTo(new File(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}