spring mvc实现文件上传
1、导入jar包(spring核心包等略)
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- 文件上传组件 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
我这里分别用的1.3.2和1.3.1
2、spring-mvc.xml文件中加入配置
<!-- 多部分文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传最大大小 单位:字节 -->
<property name="maxUploadSize" value="104857600" />
<!-- 写到磁盘之前最大大小,超过依然能上传,但是不会存到内存中 -->
<property name="maxInMemorySize" value="4096" />
<!-- 编码方式 默认ISO8859-1 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
3、后台代码
@RequestMapping("/fileUpload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IllegalStateException, IOException {
String path = "E:/" + new Date().getTime() + file.getOriginalFilename();
File newFile = new File(path);
// 通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(newFile);
return "success";
}
4、前台代码
<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
</body>
</html>
注意method、ectype是固定写法,file的name属性要和后台的@RequestParam("")里面的值要一致