Spring MVC does special care to upload file to server. It makes file upload an easy work for web application developers. Spring MVC library jar provides CommonsMultipartResolver class that makes special care to form submitted using “multipart/form-data” encode type. We can also specify max file size in this resolver.
Tools Used:
- Spring MVC 3.0.3
- Eclipse Indigo 3.7
- Tomcat 6
- Jdk 1.6
- Apache Common File Upload 1.2.0
- Apache Common IO 2.0.1
As you can see, we need two more jar files to upload file to server using Spring MVC. The name of the jar files are :
- commons-io-2.0.1.jar
- commons-fileupload-1.2.1.jar
Step1: Registering CommonsMultipartResolver in Spring MVC Configuration file
We must first register CommonsMultipartResolver class in Spring MVC configuration file so that Spring can handle multipart form data.
2 |
< bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" >
|
5 |
< property name = "maxUploadSize" value = "100000" />
|
The property “maxUploadSize” can be used to specify the max size of the file that can be uploaded to server. If we try to upload a file that is greater that the size specified in the property then Spring will through MaxUploadSizeExceededException. Later we will also learn how to handle this exception to show user friendly message when file is larger.
Step2: Creating file upload form
01 |
package com.raistudies.domain;
|
03 |
import org.springframework.web.multipart.commons.CommonsMultipartFile;
|
05 |
public class UploadForm {
|
07 |
private String name = null ;
|
08 |
private CommonsMultipartFile file = null ;
|
10 |
public String getName() {
|
13 |
public void setName(String name) {
|
16 |
public CommonsMultipartFile getFile() {
|
19 |
public void setFile(CommonsMultipartFile file) {
|
21 |
this .name = file.getOriginalFilename();
|
The file upload form contains two property one is name of type String, will contain name of the file to be upload, and the other is the file of type CommonsMultipartFile, will contain file itself. CommonsMultipartFile class is present in Apache Common Fileupload library and Spring MVC converts the form file to the instance of CommonsMultipartFile.
As our form will only contain file element, so we set the name of the file in the setter method of file attribute.
Step3: Creating controller class for file upload
01 |
package com.raistudies.controllers;
|
06 |
@RequestMapping (value= "/FileUploadForm.htm" )
|
07 |
public class UploadFormController implements HandlerExceptionResolver{
|
09 |
@RequestMapping (method=RequestMethod.GET)
|
10 |
public String showForm(ModelMap model){
|
11 |
UploadForm form = new UploadForm();
|
12 |
model.addAttribute( "FORM" , form);
|
13 |
return "FileUploadForm" ;
|
16 |
@RequestMapping (method=RequestMethod.POST)
|
17 |
public String processForm( @ModelAttribute (value= "FORM" ) UploadForm form,BindingResult result){
|
18 |
if (!result.hasErrors()){
|
19 |
FileOutputStream outputStream = null ;
|
20 |
String filePath = System.getProperty( "java.io.tmpdir" ) + "/" + form.getFile().getOriginalFilename();
|
22 |
outputStream = new FileOutputStream( new File(filePath));
|
23 |
outputStream.write(form.getFile().getFileItem().get());
|
25 |
} catch (Exception e) {
|
26 |
System.out.println( "Error while saving file" );
|
27 |
return "FileUploadForm" ;
|
31 |
return "FileUploadForm" ;
|
36 |
public ModelAndView resolveException(HttpServletRequest arg0,
|
37 |
HttpServletResponse arg1, Object arg2, Exception exception) {
|
38 |
Map<Object, Object> model = new HashMap<Object, Object>();
|
39 |
if (exception instanceof MaxUploadSizeExceededException){
|
40 |
model.put( "errors" , "File size should be less then " +
|
41 |
((MaxUploadSizeExceededException)exception).getMaxUploadSize()+ " byte." );
|
43 |
model.put( "errors" , "Unexpected error: " + exception.getMessage());
|
45 |
model.put( "FORM" , new UploadForm());
|
46 |
return new ModelAndView( "/FileUploadForm" , (Map) model);
|
The UploadFormController adds the form bean on get method request and save the file included in the request form in temp directory of server in post method.
You can notice one more thing here i.e. the UploadFormController class also implements an interface HandlerExceptionResolver. It is necessary to implement this interface to handle the MaxUploadSizeExceededException that is thrown when form file is larger then the specified max file size. resolveException method shows form with error message in form while dealing with larger file size.
Step4: Creating jsp file for file upload
01 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" |
03 |
<%@ page session="true" %> |
08 |
< title >File Upload with Spring 3 MVC</ title >
|
10 |
< meta http-equiv = "Content-Type" content = "text/html; charset=windows-1251" >
|
13 |
< h1 >File Upload Form</ h1 >< br />
|
15 |
< form:form commandName = "FORM" enctype = "multipart/form-data" method = "POST" >
|
17 |
< tr >< td colspan = "2" style = "color: red;" >< form:errors path = "*" cssStyle = "color : red;" />
|
21 |
< tr >< td >Name : </ td >< td >< form:input type = "file" path = "file" /></ td ></ tr >
|
23 |
< tr >< td colspan = "2" >< input type = "submit" value = "Upload File" /></ td ></ tr >
|
The jsp file contains a form with file input. The enctype of the form must be “multipart/form-data” to send binary data like file to server.
That is all. You can deploy the war file in Tomcat 6 and hit the url in browser, you will get following form:
File Upload Form using Spring MVC
Select a very large file (more than 100KB) and click on “Upload File” button. You will get following error :
File Size Error in Upload Form Spring MVC
Now, select a file less than 100 kb and click on “Upload File” button. You will be forwarded to success page which will show you the name of the file uploaded.
File Upload Successful Page
You can download the source and war file of the example from following links:
Source: Download
War: Download
相关推荐
Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于...
主要介绍Spring MVC 的使用注解来配置的使用实例
简单的描述了spring mvc的配置示例,不包括注解方法和示例代码
基于注解配置和使用spring AOP(spring mvc框架)
这是一个Spring MVC实例 使用MVC注解配置
如果使用spring mvc 3.2+和servelt 3+容器(比如tomcat8),那么web.xml和applicationContext.xml都不是必须的,可使用基于注解的配置: 基于配置的集成例子源代码:
Spring Mvc AOP通过注解方式拦截controller等实现日志管理
网上很多人想使用注解拦截spring mvc action中的一个方法,实现方法很多,一般是通过在拦截器中分析url路径来实现, 使用自定义注解的方式来标注要拦截的 action 中的某个方法, 没有很好的解决方法, 如果通过借助spring...
采用spring3.0 mvc 注解的方式,在页面显示helloworld
清晰的注释和简单明了的代码,绝对让你瞬间掌握如何使用ajax上传的的要领,实现举一反三
Spring MVC非注解测试,用于理解spring mvc原理,然后再结合源码分析,更好的理解spring mvc
介绍 Spring 2.5 新增的 Sping MVC 注解功能,讲述如何使用注解配置替换传统的基于 XML 的 Spring MVC 配置。
后台全注解式的开发(除了必要的spring和hibernate的xml配置以外) 03. 后台通过自定义注解结合一个访问拦截器实现整个系统的权限控制 04. 系统前台采用全采用的Html+jQuery开发 05. 系统前台与后台的交互全部...
这篇文章将教你快速地上手使用 Spring 框架. 如果你手上有一本《Spring in Action》, 那么你最好从第三部分"Spring 在 Web 层的应用--建立 Web 层"开始看, 否则那将是一场恶梦! 首先, 我需要在你心里建立起 Spring...
spring mvc + spring + hibernate 全注解整合开发视频教程 06.haozip03
spring mvc maven项目,导入IDEA后无报错,需要在IDEA中...该项目使用servlet3.0规范,无web.xml,无spring.xml等配置文件,所有的配置均通过Java Config、注解搞定,项目中还集成了log4j2技术,以及前端html文件等。
spring3.0MVC注解(附实例). spring3.0MVC注解(附实例). spring3.0MVC注解(附实例).
spring mvc + spring + hibernate 全注解整合开发视频教程 12
spring mvc + spring + hibernate 全注解整合开发视频教程 11
学习Spring MVC,关于注解的Spring MVC,简单例子,关于控制器的Spring MVC,学习Spring,简单Spring MVC实例