`
starlit53
  • 浏览: 6175 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

使用Spring MVC和注释配置来实现文件上传

阅读更多

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.

1 <!-- Configure the multipart resolver -->
2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
3  
4     <!-- one of the properties available; the maximum file size in bytes -->
5     <property name="maxUploadSize" value="100000"/>
6 </bean>

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;
02  
03 import org.springframework.web.multipart.commons.CommonsMultipartFile;
04  
05 public class UploadForm {
06  
07     private String name = null;
08     private CommonsMultipartFile file = null;
09  
10     public String getName() {
11         return name;
12     }
13     public void setName(String name) {
14         this.name = name;
15     }
16     public CommonsMultipartFile getFile() {
17         return file;
18     }
19     public void setFile(CommonsMultipartFile file) {
20         this.file = file;
21         this.name = file.getOriginalFilename();
22     }
23 }

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;
02  
03 //imports has been removed to make the code short. You can get full file by downloading it from bellow.
04  
05 @Controller
06 @RequestMapping(value="/FileUploadForm.htm")
07 public class UploadFormController implements HandlerExceptionResolver{
08  
09     @RequestMapping(method=RequestMethod.GET)
10     public String showForm(ModelMap model){
11         UploadForm form = new UploadForm();
12         model.addAttribute("FORM", form);
13         return "FileUploadForm";
14     }
15  
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();
21             try {
22                 outputStream = new FileOutputStream(new File(filePath));
23                 outputStream.write(form.getFile().getFileItem().get());
24                 outputStream.close();
25             catch (Exception e) {
26                 System.out.println("Error while saving file");
27                 return "FileUploadForm";
28             }
29             return "success";
30         }else{
31             return "FileUploadForm";
32         }
33     }
34  
35     @Override
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.");
42         else{
43             model.put("errors""Unexpected error: " + exception.getMessage());
44         }
45         model.put("FORM"new UploadForm());
46         return new ModelAndView("/FileUploadForm", (Map) model);
47     }
48 }

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" %>
04  
05 <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
06 <html xmlns="http://www.w3.org/1999/xhtml">
07     <head>
08         <title>File Upload with Spring 3 MVC</title>
09  
10         <meta http-equiv="Content-Type" content="text/html; charset=windows-1251" >
11     </head>
12     <body>
13         <h1>File Upload Form</h1><br />
14  
15         <form:form commandName="FORM" enctype="multipart/form-data" method="POST">
16         <table>
17          <tr><td colspan="2" style="color: red;"><form:errors path="*" cssStyle="color : red;"/>
18  
19          ${errors}
20          </td></tr>
21          <tr><td>Name : </td><td><form:input type="file" path="file" /></td></tr>
22  
23          <tr><td colspan="2"><input type="submit" value="Upload File" /></td></tr>
24         </table>
25  
26         </form:form>
27     </body>
28 </html>

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

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

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

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 MVC框架中,文件上传是一项常见的功能,而实现文件上传进度条则能提供更好的用户体验。这个场景通常涉及到前端的JavaScript或jQuery库(如jQuery File Upload)与后端的Spring MVC控制器之间的交互,以及...

    Spring MVC 的注解使用实例

    在Spring MVC框架中,注解的使用极大地简化了配置,提高了开发效率。Spring MVC通过注解可以实现控制器、方法映射、模型数据绑定、视图解析等关键功能。本实例将深入探讨Spring MVC中常见的注解及其应用。 1. `@...

    Spring MVC + Mybatis+Spring实现的个人博客系统

    这是一个基于Spring MVC、Mybatis和Spring框架实现的个人博客系统,涵盖了Web开发中的后端架构设计、数据库管理和前端展示等多个方面。以下将详细介绍这个系统的关键知识点: **1. Spring MVC** Spring MVC是Spring...

    spring MVC配置详解

    Handler 可以使用注解方式或 XML 配置方式来实现。 六、ViewResolver 配置 ViewResolver 是 Spring MVC 框架中负责将模型数据渲染到视图中的组件。我们可以使用 InternalResourceViewResolver 或其他视图解析器来...

    spring+spring mvc+mybatis框架整合实现超市货物管理系统

    在本文中,我们将深入探讨如何使用JavaEE技术栈,特别是Spring、Spring MVC和MyBatis框架,来构建一个超市货物管理系统的实现。这个系统涵盖了基本的登录功能以及与MySQL数据库的交互,包括增删改查操作和分页显示。...

    spring 与 spring mvc 整合 配置讨论

    本文将深入探讨Spring与Spring MVC的整合配置,并结合标签"源码"和"工具"来解析相关的技术细节。 首先,Spring框架的核心特性包括依赖注入(Dependency Injection, DI)和面向切面编程(Aspect-Oriented ...

    SevenDay-Spring MVC(基于Spring MVC实现文件上传与下载)的源代码

    在这个"SevenDay-Spring MVC 实现文件上传与下载"项目中,我们将深入探讨如何利用Spring MVC来处理文件的上传和下载。 首先,`pom.xml`是项目的核心配置文件,它定义了项目的依赖管理。在这个项目中,可以看到对`...

    Spring MVC 文件上传下载 后端 - Java.zip

    通过阅读"Spring MVC 文件上传下载 后端 - Java.doc"文档,你可以深入理解如何在实际项目中实现这些功能,包括具体的代码示例、配置细节和最佳实践。这份文档可能会涵盖以上所有知识点,帮助开发者更好地掌握Spring ...

    Spring MVC实例 MVC注解配置

    - 在Spring MVC中,我们不再需要传统的XML配置文件来定义控制器、视图解析器等组件。通过使用注解,可以在类或方法级别直接声明其功能。例如,`@Controller`注解标记一个类作为处理HTTP请求的控制器,而`@...

    Spring MVC 教程快速入门 深入分析

    六、Spring MVC mvc.xml配置文件片段讲解:Spring MVC通过配置文件来定义处理器映射、视图解析器、静态资源处理等。配置文件对于整个框架的运行至关重要。 七、Spring MVC如何访问到静态的文件:描述了如何配置...

    ssm框架--spring mvc实现文件上传

    总的来说,"ssm框架--spring mvc实现文件上传"项目涵盖了Spring MVC的文件上传机制、数据库设计、MyEclipse的使用以及测试实践等多个知识点。理解并掌握这些内容,对于提升Java Web开发能力具有重要意义。

    spring mvc 读取配置文件

    这篇博客“spring mvc 读取配置文件”将深入探讨如何在Spring MVC中读取和使用配置文件,以及相关工具的应用。 首先,Spring MVC中的配置文件通常是指XML配置文件,如`applicationContext.xml`或`servlet-context....

    Spring MVC实现文件的上传下载

    在Spring MVC中实现文件的上传和下载是常见的需求,这涉及到处理multipart/form-data类型的表单数据,以及对文件的存储和读取操作。 首先,让我们了解文件上传的基本流程。当用户通过表单提交带有文件的请求时,...

    spring mvc shiro的配置使用.zip_DEMO_spring mvc_spring mvc shiro

    - **princeframework-quyue-boss.zip**:这个可能是项目的一个特定模块或子项目,可能包含了 Spring MVC 和 Shiro 集成的具体实现,包括 Controller、Service、DAO、配置文件等。 通过这个 "spring mvc shiro" 的 ...

    Spring MVC jar包

    而`spring-framework-2.5.6-with-docs.zip`可能包含了Spring 2.5.6的源码和文档,帮助开发者了解Spring MVC的内部实现和最佳实践。 总之,这个压缩包提供了开发基于Spring MVC和Hibernate的Java Web应用所需要的...

    spring mvc案例+配置+原理详解+架包

    这个压缩包包含了关于Spring MVC的案例、配置和原理的详细资料,对于初学者来说,是深入理解该框架的良好资源。 一、Spring MVC 基本概念 1. **模型-视图-控制器(MVC)**:MVC是一种设计模式,将业务逻辑、数据...

    Spring MVC使用Demo

    这个"Spring MVC使用Demo"提供了实践操作,帮助开发者深入理解Spring MVC的开发环境配置、注解的使用以及工作原理。 首先,Spring MVC的设计模式基于Model-View-Controller(MVC),它将应用程序的业务逻辑、数据和...

    使用Spring 2.5 基于注解驱动的 Spring MVC详解

    在 Spring 2.5 中,Spring MVC 框架引入了注解驱动功能,使得开发者可以使用注解来配置 Controller,代替传统的基于 XML 的配置方式。这种方式使得 Controller 的开发变得更加灵活和方便。 使用 @Controller 注解 ...

    spring mvc 3.2 rest配置 文件

    7. **CORS支持** - 对于跨域资源共享(CORS),Spring MVC提供了`CorsRegistry`和`CorsConfiguration`来配置允许哪些来源进行访问。 8. **Validation** - 使用JSR-303/JSR-349提供的注解进行数据验证,例如`@Not...

Global site tag (gtag.js) - Google Analytics