目录
Springmvc文件上传
依赖的jar包
commons-io
commons-upload
Spring 核心依赖包:bean context aop context core web webmvc expression
web.xml相关配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>springmvc_upload</display-name>
<filter>
<filter-name>characterencoding</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterencoding</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
注意点:
- springmvc的核心配置文件一定在DispatcherServlet处配置其具体位置,而不是
- 映射的虚拟路径可以是"/"、"/"、".do"等,但是不要写成"/*.do"
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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 开启mvc的注解 -->
<mvc:annotation-driven />
<!-- 扫描包 -->
<context:component-scan base-package="com.zrm.controller"></context:component-scan>
<!-- 配置视图解析器 -->
<bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置文件解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10240000"></property>
<property name="maxInMemorySize" value="4096000"></property>
</bean>
</beans>
注意点:
- 上传的文件大小不得超过文件解析器中maxUploadSize设置的大小,否则会报错
- 若是在web.xml的url-pattern中设置如/*拦截了静态资源,可在此处添加类似这样的设置来放行静态资源,最好把静态资源放置在wencontent下而非WEB-INF(访问权限受限)
单文件上传
controller层Java代码
@Controller
public class UploadCtrl {
@RequestMapping("/toUpload.do")
public String toUpload() {
return "upload";
}
@RequestMapping("/upload.do")
public ModelAndView upload(HttpServletRequest req,@RequestParam("file")CommonsMultipartFile file) {
String path = req.getServletContext().getRealPath("/upload");
String name = file.getOriginalFilename();
System.out.println("文件名:"+name);
InputStream is = null;
OutputStream os = null;
try {
is = file.getInputStream();
os = new FileOutputStream(new File(path,name));
byte[] bytes = new byte[1024];
int len =0;
while((len=is.read(bytes))!=-1) {
os.write(bytes,0,len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(is!=null)
is.close();
if(os!=null)
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return new ModelAndView("index");
}
注意点:
- CommonsMultipartFile file处必须使用注解@RequestParam("file")为其注入请求中的file属性值,否则CommonsMultipartFile会自己去尝试初始化file,从而报错(找不到CommonsMultipartFile的file值)
通过 "String path = req.getServletContext().getRealPath("/upload");" 将"/upload"这个虚拟路径映射为webcontent下的真实路径。
相关jsp代码:upload.jsp
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
file:<input type="file" name="file"/><input type="submit" value="上传"/>
</form>
</body>
多文件批量上传
controller层Java代码
@RequestMapping("/toBatchUpload.do")
public String toBatchUpload() {
return "batchUpload";
}
@RequestMapping("/batchUpload.do")
public ModelAndView batchUpload(HttpServletRequest req,@RequestParam("file")CommonsMultipartFile[] file) {
String path = req.getServletContext().getRealPath("/upload");
String name = null;
InputStream is = null;
OutputStream os = null;
byte[] bytes = new byte[1024];
int len =0;
for (int i = 0; i < file.length; i++) {
try {
name = file[i].getOriginalFilename();
is = file[i].getInputStream();
System.out.println("文件名:"+name);
os = new FileOutputStream(new File(path,name));
while((len=is.read(bytes))!=-1) {
os.write(bytes,0,len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(is!=null)
is.close();
if(os!=null)
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return new ModelAndView("index");
}
通过for循环,重复执行单文件上传代码
相关jsp代码:batchUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Page</title>
<script src="${pageContext.request.contextPath }/js/jquery-2.1.0.min.js" type="text/javascript"></script>
</head>
<body>
<form action="batchUpload.do" method="post" >
file:<input type="file" name="file"/>
<input id="add" type="button" value="添加">
<input type="submit" value="上传"/>
<div id="fileList"></div>
</form>
</body>
<script type="text/javascript">
$("#add").click(function(){
var field = "<p>选择文件:<input type='file' name='file'/><input type='button' value='删除 ' onclick='del(this);' /></p>";
$("#fileList").append(field);
});
function del(obj){
$(obj).parent().remove();
};
</script>
</html>
index.jsp
<body>
上传成功
</body>
注意点:
- jquery的基本语法就是以function,所以del()函数需要单独定义,而不能将其嵌套在$().ready里面。总结起来就是,使用时可嵌套,但是定义时不可嵌套
enctype="multipart/form-data"上传的文件类型不能忘了
项目结构
项目源码已上传至 github fileupload