File Upload in Spring MVC

File Upload in Spring MVC

In general, in web applications, it is very frequent to perform upload operations in order to upload files from client to Server.

To perform File Upload operation in Spring WEB MVC applications, Spring WEB MVC frameworkhas provided some predefined library in the form of
“org.springframework.web.multipart.commons.CommonsMultipartResolver”

If we want to perform Upload operation in Spring WEB MVC applications then we have to use the following steps.

1. Prepare a user form with File components

  • In User form, we must specify “POST” as “method” attribute in form tag.
  • in User form, we must provide “multipart/form-data” as “enctype” attribute in form tag.

uploadform.jsp

<form method="POST" action="upload" enctype="multipart/form-data">
   <center>
      <table>
         <tr>
            <td>File1</td><td><input type="file" name="file"/></td>
         </tr>
      </table>
   </center>
</form>

2. Prepare Controller class with MultipartFile parameter in action method

UploadController.java

@Controller
public class UploadController {
   -----
   @RequestMapping(value="/upload", method=RequestMethod.POST)
   public ModelAndView uploadFiles(@RequestParam MultipartFile file) {
      String status = "";
      try{
         String file_Name = multipartFile.getOriginalFilename();
         FileOutputStream fos = new FileOutputStream("E:/uploads/"+file_Name);
         byte[] bt = multipartFile.getBytes();
         fos.write(bt);
         status = "SUCCESS";
      } catch (Exception e) {
         status = "FAILURE";
         e.printStackTrace();
      }
      return new ModelAndView("status", "status", status);
   }
}

3. Configure CommonsMultipartResolver class as bean with the name “multipartResolver” in spring configuration file

ds-servlet.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

Note

For File Upload operation, Spring Framework is using Commons File Upload library internally, so that, we must provide the following JAR files in web application lib folder along with all Spring JARs.

commons-fileupload-1.4.jar
commons-io-2.6.jar

E.g

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <jsp:forward page="upload"/>
</body>
</html>

uploadform.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
   <head>
      <meta charset="ISO-8859-1">
      <title>Insert title here</title>
   </head>
   <body>
      <h2 style="color: red;" align="center">File Upload Form</h2>
      <form method="POST" action="upload" enctype="multipart/form-data">
         <center>
            <table>
               <tr>
                  <td>File1</td>
                  <td><input type="file" name="file"/></td>
               </tr>
               <tr>
                  <td>File2</td>
                  <td><input type="file" name="file"/></td>
               </tr>
               <tr>
                  <td>File3</td>
                  <td><input type="file" name="file"/></td>
               </tr>
               <tr>
                  <td><input type="submit" value="Upload"/></td>
               </tr>
            </table>
         </center>
      </form>
   </body>
</html>

status.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
   <head>
      <meta charset="ISO-8859-1">
      <title>Insert title here</title>
   </head>
   <body>
      <h1 style="color: red;" align="center">Files Upload Status: ${status}</h1>
   </body>
</html>

UploadController.java

package com.ashok.spring.mvc.controller;

import java.io.FileOutputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UploadController {
    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String showUploadForm() {
        return "uploadform";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView uploadFiles(@RequestParam MultipartFile[] file) {
        String status = "";
        try {
            for (MultipartFile multipartFile: file) {
                String file_Name = multipartFile.getOriginalFilename();
                FileOutputStream fos = new FileOutputStream("/home/ashok/data/" + fileName);
                byte[] bt = multipartFile.getBytes();
                fos.write(bt);
                status = "SUCCESS";
            }
        } catch (Exception e) {
            status = "FAILURE";
        }
        return new ModelAndView("status", "status", status);
    }
}

ds-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">
   <context:annotation-config/>
   <context:component-scan base-package="com.ashok.spring.mvc.controller"/>
   <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/"/>
      <property name="suffix" value=".jsp"/>
   </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
   id="WebApp_ID" version="4.0">
   <display-name>MVC</display-name>
   <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      <welcome-file>default.html</welcome-file>
      <welcome-file>default.htm</welcome-file>
      <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
   <servlet>
      <servlet-name>ds</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>ds</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>
File Upload in Spring MVC
Scroll to top