Spring 4 MVC - File Upload Example

By Yashwant Chavan, Views 52910, Date 01-Jan-2017

In this tutorial, You will learn how to Upload Files using Spring 4 MVC application. This example will help you how to configure MultipartResolver using java config. To upload files I am using Apache commons fileupload API.

tags spring

Spring 4 Eclipse project set up

Spring 4 MVC File Upload Example - Eclipse project setup

Tools and Technologies

  1. Apache Maven 3.0.4
  2. JDK 1.8
  3. Spring 4.1.4.RELEASE

pom.xml

As we are using Maven project. Let's define the spring 4 specific maven dependencies.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.technicalkeeda</groupId>
    <artifactId>Spring4Examples</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>Spring4Examples</name>
    <description></description>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <spring.version>4.1.4.RELEASE</spring.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>
</project>

Spring 4 Application Configuration

@Configuration annotation imports the Spring configuration. @Configuration objects are managed as Spring beans within the container, imported configurations are used to injected using @Autowired or @Inject.

@ComponentScan is equivalent to <context:component-scan base-package="..." used to lookup the beans and components classes in the spring context.

@EnableWebMvc annotation is used to enable Spring MVC.

To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory.

Configure CommonsMultipartResolver bean which is implementation for Apache Commons FileUpload. You can configure different bean properties like "maxUploadSize", "maxInMemorySize" and "defaultEncoding" etc.

Configure static resources handlers - Add handlers to serve static resources such as images, js, and, css files from specific locations.

package com.technicalkeeda.configuration;

import java.io.IOException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan(basePackages = "com.technicalkeeda")
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver getResolver() throws IOException {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        // no limit
        resolver.setMaxUploadSize(-1);
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
    }

}

WebApplicationInitializer Configuration

Earlier we used to define web.xml to declare the dispatcher related configurations. Now we are using 100% code base (annotation and java config ) approach to doing the application configuration.

WebApplicationInitializer interface is implemented using Servlet 3.0+ style, Which is used to configure the ServletContext programmatically rather than traditional web.xml-based approach.

package com.technicalkeeda.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class ApplicationInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {

        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(ApplicationConfig.class);
        ctx.setServletContext(container);

        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));

        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }

}

Spring MVC File Upload Controller

Let's create a simple controller class FileuploadController and annotate it with @Controller. The @Controller annotation indicates that a particular class serves the role of a controller.

Now add upload() method along with @RequestMapping annotation. The dispatcher will scan such annotated classes for mapped methods and detect the respected @RequestMapping annotation.

@Autowired ServletContext - ServletContext is the configuration object which is created when web application is started. It holds information about different initialization parameters which is configured in web application.

ServletContext.getRealPath(String path) method is used to get the real path of the resource. In our case we used to get the real path of the /WEB-INF/uploaded folder.

@RequestParam("file") List<MultipartFile> files - Handles the HTTP multi-part file upload request. You can upload single or multiple files also.

MultipartFile.transferTo(File destination) method transfers the uploaded file to the given destination file.

Once the files are successfully uploaded then forward the request to "success" view. Which will display the list of uploaded files.

package com.technicalkeeda.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
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;

import com.technicalkeeda.bean.FileInfo;

@Controller
public class FileuploadController {
    @Autowired
    ServletContext context;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView upload(@RequestParam("file") List < MultipartFile > files) {
        List < FileInfo > uploadedFiles = new ArrayList < FileInfo > ();
        if (!files.isEmpty()) {
            try {
                for (MultipartFile file: files) {
                    String path = context.getRealPath("/WEB-INF/uploaded") + File.separator +
                        file.getOriginalFilename();
                    File destinationFile = new File(path);
                    file.transferTo(destinationFile);
                    uploadedFiles.add(new FileInfo(destinationFile.getName(), path));
                }

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

        }
        ModelAndView modelAndView = new ModelAndView("success");
        modelAndView.addObject("files", uploadedFiles);
        return modelAndView;
    }
}

FileInfo Pojo

This is simple pojo (FileInfo) class which represents the uploaded file information like file name and path.

package com.technicalkeeda.bean;

public class FileInfo {

    private String name;
    private String path;

    public FileInfo(String name, String path) {
        super();
        this.name = name;
        this.path = path;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

}

Default Page (index.jsp)

Create index.jsp page, Which is default view of the Spring MVC application. Which contains File upload form along with enctype attribute for multipart content (enctype="multipart/form-data"). I have defined a form control for user input, Which helps to select the files to upload.

<form method="post" action='upload' enctype="multipart/form-data">
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Spring 4 MVC - File Upload Example</title>
        <link type="text/css" href="<c:url value='/assets/css/bootstrap.min.css' />" rel="stylesheet" />
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <h1>Spring 4 MVC - File Upload Example</h1>
                    <form method="post" action='upload' enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="file1">File Input 1</label>
                            <input type="file" name="file" id="file1">
                        </div>
                        <div class="form-group">
                            <label for="file2">File Input 2</label>
                            <input type="file" name="file" id="file2">
                        </div>
                        <button type="submit" class="btn btn-success">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

success.jsp

Create success.jsp under /WEB-INF/jsp folder, Which will display the upload files information.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Spring 4 MVC - File Upload Example</title>
        <link type="text/css" href="<c:url value='/assets/css/bootstrap.min.css' />" rel="stylesheet" />
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <h2>Uploaded File Details</h2>
                    <c:forEach items="${files}" var="file">
                        <div class="row" style="border:1px solid #ccc; margin:5px;">
                            <div class="col-md-4">
                                <b><c:out value="${file.name}" /></b>
                            </div>
                            <div class="col-md-4">
                                <c:out value="${file.path}" />
                            </div>
                        </div>
                    </c:forEach>
                </div>
            </div>
        </div>
    </body>
</html>

Deploy and Execute

Enter URI (http://localhost:8080/Spring4Examples) in your browser, It will render the index.jsp page, then select the respected files which you to upload.

Spring 4 MVC File Upload Form

Uploaded Files (success.jsp) View

Spring 4 MVC File Upload Success Page
Yashwant Chavan

Yashwant Chavan

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan@gmail.com