Spring mvc使用jakarta的commons fileupload来支持文件上传。
先修改pom.xml,增加对commons fileupload lib包的引用。
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
再修改spring的context 配置文件,增加对MultipartResolver的引用。
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000" />
</bean>
增加uploader的controller类
@RequestMapping("/uploader")
public String uploader(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file,
HttpSession session){
if (!file.isEmpty()) {
System.out.println(file.getSize());
}
return "helloWorld";
}
增加文件上传的jsp页面
<html>
<head>
<title>file upload test</title>
</head>
<body>
<form method="post" action="uploader" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="file" name="file" />
<input type="submit" />
</form>
</body>
</html>