Aug
9
2015

Spring MVC file upload example in java

Hi in this tutorial of spring tutorial we will see how spring provide  help in file upload with CommonsMultipartResolver. In this tutorial we will see how we can store filename in database and the related file in some directory. In Servlet file upload example in java tutorial i have meantion why we should store file name only instead of complete file.

Project Structure

spring file upload in java

 

In project structure we have a folder with name documentsfile to store uploaded files.  Now let see coding part of this structure. Complete code of this availabe in git repository .


 

web.xml

This is starting point of any web application.

ContextLoaderListener load all the class path configuration files. applicationContext-hibernate.xml contatin information for hibernate stuff like session factory information and datasource information and entity class list etc.

In Web application there are two type application context :

  • Root Application Context
  • Servlet Specific Application Context

Bean defined in Root Application Context is available in all application while bean defiled in servlet specific context are visible in that servler context only. We will see in depth ablout it in another tutorial.

spring-servlet.xml

This is our spring configuration file that contaion information for spring view resolver , DAO beans , Service Bean and multipartResolver bean information.

<context:component-scan base-package=”com.javafreakers.controller” /> will register all classes in this package as spring bean.

<bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”prefix” value=”/WEB-INF/views/” />
<property name=”suffix” value=”.jsp” />
</bean>

Above will tell view resolver to look for view in WEB-INF/views directory with .jsp suffix while looking for view that need to return upon a request.

<tx:annotation-driven/> will enable annotation based transaction configuration in our project.

applicationContext-hibernate.xml

It contain all the necessary information for the use of hibernate like database name, database driver to connect with database ,batabase username and password etc.

In addition it also has PropertyPlaceholderConfigurer bean which locate jdbc.properties file in class path . It is always good practice to use properties files to supply such information rather than hard code these information.

jdbc.properties

This file is simply provide information for hibernate jdbc connection with database. We use PropertyPlaceholderConfigurer class of spring to locate this file in class path.

index.jsp

This file simply redirect to adddetail.jsp page through ProductController. When we will run this project then index.jsp has been mention as welcome file in web.xml. In index.jsp we have simply redirected request to productform.html . In web.xml we have mention in <url-pattern>*.html</url-pattern> that any request with of .html will be handled by DispatcherServlet class of spring. DispatcherServlet will look at RequestMapping for this request in controller bean classes. RequestMapping that matches the incomming request, method of that RequestMapping will be executed. For more detail once go through spring web flow tutorial.

addProduct.jsp

Simple html form that has product name, manufaturer name and picture of product. Here the most important thing is enctype=”multipart/form-data” in form tag. Without it file upload is not possible. Once this question was also asked to me in an interview and fortunatally i managed to give answer of it. Also method type is post. Form action=”saveproduct.html”  means when user will submit this form then DispatcherServlet will look for saveproduct.html in RequestMapping of controllers and method of that mapping will execute.

Note that in  <input type=”file” name=”file”  id=”documentLinkStr” > name has to be same as the variable name in FileUpload.java file of model package.


 

ProductController.java 

DispatcherServlet look in controller for request mapping.  Based on value returned from controller InternalResourceViewResolver return response. When addproduct is return from productForm method then InternalResourceViewResolver  return addproduct.jsp.

The below lines are most important in spring fileupload part. It save files in documentsfile folder, also set path of this file in product object.

MultipartFile file = fileUpload.getFile();
try {
file.transferTo(new File(request.getRealPath(“/”)+”/documentsfile/”+file.getOriginalFilename()));
product.setDocumentLinkStr(“/documentsfile/”+file.getOriginalFilename());
}

We have also injected productService in controller bean through autowiring .

ProductServiceImpl.java 

In product service we have just set date of manufacturing and date of expiration of product and passed it to dao to save it. The date of expiration is set thirty days from date of manufactring. The response return from dao is returned back to controller.

We have injected productDao object through autowiring .

ProductDaoImpl.java

In ProductDaoImpl we have injected sessionFactory object and used this object to save product object. Note that we have used @Transactional annotation above the saveProduct method. This is required to make any database transaction .  It define transaction scope . In configuration file we have define annotation driven transaction configuration through <tx:annotation-driven />.

Save() method save object in session and return a identifier associated with object.

Product.java 

Product is our entity class. There are some properties and some getters and setters method of it. There is nothing much to explain about it.

FileUpload.java

This is perticulerly used for fileupload support . It has only one field of type MultipartFile. Note that name of this field and name=”file” in the form of input type=”file” element has to be same. 

Output :spring file upload in java form

 

Hibernate: insert into Product (product_image_link, date_of_expiration, date_of_manufacture, manufacturer_name, product_name) values (?, ?, ?, ?, ?)

That is all in this post . You can download code of it from Git Repository.  If you get any issue you can raise it on git as well as you can also email me or comment.

Comments are closed.