Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Spring MVC File Upload


Spring MVC provides easy way to upload files, it may be image or other files. Let’s see a simple example to upload file using Spring MVC.


Required Jar files

To run this example, you need to load:

  • Spring Core jar files
  • Spring Web jar files
  • commons-fileupload.jar and commons-io.jar file

download all the jar files for spring including core, web, aop, mvc, j2ee, remoting, oxm, jdbc, orm etc.

download commons-io.jar

download commons-fileupload.jar


Spring MVC File Upload Example

Create images directory

Create “images” directory in your project because we are writing the code to save all the files inside “/images” directory.

index.jsp

  1. <a href=“uploadform”>Upload Image</a>

Emp.java

  1. package com.Kreationnext;
  2. import java.io.BufferedOutputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import javax.servlet.ServletContext;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import javax.servlet.http.HttpSession;
  9. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  10. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  11. import org.springframework.stereotype.Controller;
  12. import org.springframework.web.bind.annotation.ModelAttribute;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RequestMethod;
  15. import org.springframework.web.bind.annotation.RequestParam;
  16. import org.springframework.web.multipart.commons.CommonsMultipartFile;
  17. import org.springframework.web.servlet.ModelAndView;
  18. @Controller
  19. public class HelloController {
  20.     private static final String UPLOAD_DIRECTORY =“/images”;
  21.     private static final int THRESHOLD_SIZE     = 1024 * 1024 * 3;  // 3MB
  22.     @RequestMapping(“uploadform”)
  23.     public ModelAndView uploadForm(){
  24.         return new ModelAndView(“uploadform”);
  25.     }
  26.     @RequestMapping(value=“savefile”,method=RequestMethod.POST)
  27.     public ModelAndView saveimage( @RequestParam CommonsMultipartFile file,HttpSession session) throws Exception
  28.     {
  29.     /*DiskFileItemFactory factory = new DiskFileItemFactory();
  30.     factory.setSizeThreshold(THRESHOLD_SIZE);
  31.     factory.setRepository(new File(System.getProperty(“java.io.tmpdir”)));   
  32.     ServletFileUpload upload = new ServletFileUpload(factory);*/
  33.     ServletContext context = session.getServletContext();
  34.     String uploadPath = context.getRealPath(UPLOAD_DIRECTORY);
  35.     System.out.println(uploadPath);
  36.     byte[] bytes = file.getBytes();
  37.     BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(
  38.          new File(uploadPath + File.separator + file.getOriginalFilename())));
  39.     stream.write(bytes);
  40.     stream.flush();
  41.     stream.close();
  42.     return new ModelAndView(“uploadform”,“filesuccess”,“File successfully saved!”);
  43.     }
  44. }

web.xml

  1. <?xml version=“1.0” encoding=“UTF-8”?>
  2. <web-app version=“2.5”
  3.     xmlns=“http://java.sun.com/xml/ns/javaee”
  4.     xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
  5.     xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee 
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”>
  7.  <servlet>
  8.     <servlet-name>spring</servlet-name>
  9.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10.     <load-on-startup>1</load-on-startup>
  11. </servlet>
  12. <servlet-mapping>
  13.     <servlet-name>spring</servlet-name>
  14.     <url-pattern>/</url-pattern>
  15. </servlet-mapping>
  16. </web-app>

spring-servlet.xml

Here, you need to create a bean for CommonsMultipartResolver.

  1. <?xml version=“1.0” encoding=“UTF-8”?>
  2. <beans xmlns=“http://www.springframework.org/schema/beans”
  3.     xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
  4.     xmlns:p=“http://www.springframework.org/schema/p”
  5.     xmlns:context=“http://www.springframework.org/schema/context”
  6.     xsi:schemaLocation=”http://www.springframework.org/schema/beans  
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8. http://www.springframework.org/schema/context  
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd”>  
  10. <context:component-scan base-package=“com.Kreationnext”></context:component-scan>
  11. <bean class=“org.springframework.web.servlet.view.InternalResourceViewResolver”>
  12. <property name=“prefix” value=“/WEB-INF/jsp/”></property>
  13. <property name=“suffix” value=“.jsp”></property>
  14. </bean>
  15. <bean id=“multipartResolver” class=“org.springframework.web.multipart.commons.CommonsMultipartResolver”/>
  16. </beans>

uploadform.jsp

Here form must be method=”post” and enctype=”multipart/form-data”.

  1. <%@taglib uri=“http://www.springframework.org/tags/form” prefix=“form”%>
  2. <!DOCTYPE html>
  3. <html>
  4.  <head>
  5.  <title>Image File Upload</title>
  6.  </head>
  7.  <body>
  8. <h1>File Upload Example – Kreationnext</h1>
  9. <h3 style=“color:red”>${filesuccess}</h3>
  10. <form:form method=“post” action=“savefile” enctype=“multipart/form-data”>
  11. <p><label for=“image”>Choose Image</label></p>
  12. <p><input name=“file” id=“fileToUpload” type=“file” /></p>
  13. <p><input type=“submit” value=“Upload”></p>
  14. </form:form>
  15. </body>
  16. </html>

Output

spring-mvc-file-upload-output1

spring-mvc-file-upload-output2

spring-mvc-file-upload-output3

Go to the path printed on the server console, to see the uploaded file.


Download Spring MVC File Upload Example

We have created this application in MyEclipse IDE which already provides the jar files. If you use eclipse or other IDE’s, you need to load the jar file for spring MVC.

Comments

comments