Sunday, September 15, 2019

Spring MVC File Upload Example

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
1) Download all the jar files for spring including core, web, aop, mvc, j2ee, remoting, oxm, jdbc, orm etc.


 Download commons-io.jar

3) Download commons-fileupload.jar

Spring MVC File Upload Steps (Extra than MVC)

1) Add commons-io and fileupload.jar files
2) Add entry of CommonsMultipartResolver in spring-servlet.xml
  1. <bean id="multipartResolver"   
  2. class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>  
3) Create form to submit file. Method name must be "post" and enctype "multiple/form-data".
  1. <form action="savefile" method="post" enctype="multipart/form-data">  
  2. Select File: <input type="file" name="file"/>  
  3. <input type="submit" value="Upload File"/>  
  4. </form>  
4) Use CommonsMultipartFile class in Controller.
  1. @RequestMapping(value="/savefile",method=RequestMethod.POST)  
  2. public ModelAndView upload(@RequestParam CommonsMultipartFile file,HttpSession session){  
  3.         String path=session.getServletContext().getRealPath("/");  
  4.         String filename=file.getOriginalFilename();  
  5.           
  6.         System.out.println(path+" "+filename);  
  7.         try{  
  8.         byte barr[]=file.getBytes();  
  9.           
  10.         BufferedOutputStream bout=new BufferedOutputStream(  
  11.                  new FileOutputStream(path+"/"+filename));  
  12.         bout.write(barr);  
  13.         bout.flush();  
  14.         bout.close();  
  15.           
  16.         }catch(Exception e){System.out.println(e);}  
  17.         return new ModelAndView("upload-success","filename",path+"/"+filename);  
  18.     }  
5) Display image in JSP.
  1. <h1>Upload Success</h1>  
  2. <img src="${filename}"/>  

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.javatpoint;  
  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.   
  19. @Controller  
  20. public class HelloController {  
  21.     private static final String UPLOAD_DIRECTORY ="/images";  
  22.       
  23.     @RequestMapping("uploadform")  
  24.     public ModelAndView uploadForm(){  
  25.         return new ModelAndView("uploadform");    
  26.     }  
  27.       
  28.     @RequestMapping(value="savefile",method=RequestMethod.POST)  
  29.     public ModelAndView saveimage( @RequestParam CommonsMultipartFile file,  
  30.            HttpSession session) throws Exception{  
  31.   
  32.     ServletContext context = session.getServletContext();  
  33.     String path = context.getRealPath(UPLOAD_DIRECTORY);  
  34.     String filename = file.getOriginalFilename();  
  35.   
  36.     System.out.println(path+" "+filename);        
  37.   
  38.     byte[] bytes = file.getBytes();  
  39.     BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(  
  40.          new File(path + File.separator + filename)));  
  41.     stream.write(bytes);  
  42.     stream.flush();  
  43.     stream.close();  
  44.            
  45.     return new ModelAndView("uploadform","filesuccess","File successfully saved!");  
  46.     }  
  47. }  

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.   
  11. <context:component-scan base-package="com.javatpoint"></context:component-scan>  
  12.   
  13. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  14. <property name="prefix" value="/WEB-INF/jsp/"></property>  
  15. <property name="suffix" value=".jsp"></property>  
  16. </bean>  
  17.   
  18. <bean id="multipartResolver"   
  19. class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>  
  20.   
  21. </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.    
  3. <!DOCTYPE html>  
  4. <html>  
  5.  <head>  
  6.  <title>Image File Upload</title>  
  7.  </head>  
  8.  <body>  
  9. <h1>File Upload Example - JavaTpoint</h1>  
  10.   
  11. <h3 style="color:red">${filesuccess}</h3>  
  12. <form:form method="post" action="savefile" enctype="multipart/form-data">  
  13. <p><label for="image">Choose Image</label></p>  
  14. <p><input name="file" id="fileToUpload" type="file" /></p>  
  15. <p><input type="submit" value="Upload"></p>  
  16. </form:form>  
  17. </body>  
  18. </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.

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...