Spring MVC provides a robust mechanism for handling file uploads in web applications. Using Spring MVC file upload, developers can easily integrate multipart file handling with the CommonsMultipartResolver. This article covers how to upload files in Spring MVC, configure MultipartResolver, and manage uploaded files efficiently. Whether you are working with image uploads, document storage, or handling large files, this article will help you build a Spring MVC file upload example step by step.
Pre-requisites:
- Eclipse IDE (or any other IDE of your choice)
- Apache Maven for dependency management
- Java 11 or higher
- Apache Tomcat 10 or higher (for deploying the application)
Steps to Create a Spring MVC File Uploading Project
Spring MVC framework provides support for CommonsMultipartResolver for uploading any kind of file for a web-based application. Here we will be creating a Spring MVC web application and configuring MultipartResolver to upload files (image) and also show them on the web.
Step 1: Create a Maven Web Application Project
Open Eclipse IDE and create a new Maven project. Select the maven-archetype-webapp archetype. Enter the Group Id (e.g., com.gfg) and Artifact Id (e.g., SpringMVCFileUpload). Click Finish to create the project.
Step 2: Project Structure
The project structure would look something like this:
Step 3: Add Dependencies in pom.xml
Let's start by adding some dependencies into the pom.xml already created after creating a maven project. The pom.xml defines all the dependencies that maven has to get and manage for you. We are going to add dependencies for Spring MVC, jakarta EE and file upload libraries.
pom.xml:
XML
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg</groupId>
<artifactId>SpringMVCFileUpload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringMVCFileUpload Maven Webapp</name>
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.23</version>
</dependency>
<!-- Jakarta Servlet API -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<!-- Jakarta JSTL -->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>2.0.0</version>
</dependency>
<!-- Apache Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.5</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- JUnit for Testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCFileUpload</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>
Step 4: Configure web.xml
The web.xml file in the WEB-INF folder defines mapping with different URLs and servlets to handle requests for those URLs. In this configuration file, we have used Jakarta EE namespace and configure the DispatcherServlet.
web.xml:
XML
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee/"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee/ https://jakarta.ee/xml/ns/jakartaee//web-app_5_0.xsd"
version="5.0">
<display-name>Spring MVC File Upload</display-name>
<servlet>
<servlet-name>gfg</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/gfg-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>gfg</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Step 5: Configure gfg-servlet.xml
This is the gfg-servlet.xml file located in "/src/main/webapp/WEB-INF/gfg.servlet.xml". This file handles all HTTP requests for web applications. The annotation-driven enable the spring @Controller function, resource-mapping helps in handling HTTP requests for all resources. The bean configuration helps in identifying and scanning the jsp located in the views folder. The component-scan locates and allocated beans according to the mentioned annotation. Also added a resource mapping to map all the resources to the view a page.
gfg-servlet.xml:
A bean with id as multipartResolver will help in instantiating the CommonsMultipartResolver.
XML
<beans xmlns="http://www.springframework.org/schema/beans/"
xmlns:context="http://www.springframework.org/schema/context/"
xmlns:mvc="http://www.springframework.org/schema/mvc/"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans/ http://www.springframework.org/schema/beans//spring-beans.xsd
http://www.springframework.org/schema/mvc/ http://www.springframework.org/schema/mvc//spring-mvc.xsd
http://www.springframework.org/schema/context/ http://www.springframework.org/schema/context//spring-context.xsd">
<context:component-scan base-package="com.gfg" />
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" cache-period="31556926"/>
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" name="viewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Configure MultipartResolver for file uploads -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>
Step 6: Create the Controller
The UploadFileController class in the com.gfg.controller has was methods for two requests to be mapped. The upload method is a get mapping and simple redirects to the fileform.jsp view page. The fileUpload method sends a Post request and redirects the showupload page. This class has three parameters CommonsMultipartFile gets the uploaded file. The file is converted into a bytes array and saved into a file using FileOutputStream, the model param is used to add the file name as an attribute in the showupload.jsp file.
UploadFileController:
Java
package com.gfg.controller;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
public class UploadFileController {
@GetMapping("/upload")
public String upload() {
return "fileform";
}
@PostMapping("/uploadfile")
public String fileUpload(@RequestParam("thisfile") CommonsMultipartFile file, HttpSession session, Model model) {
byte[] data = file.getBytes();
String filePath = session.getServletContext().getRealPath("/") + "WEB-INF" + File.separator + "resources"
+ File.separator + "image" + File.separator + file.getOriginalFilename();
try (FileOutputStream fileout = new FileOutputStream(filePath)) {
fileout.write(data);
model.addAttribute("imgName", file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
return "showupload";
}
}
Step 7: Create JSP Views
The fileform.jsp in the views folder defines the upload form with enctype as multipart/form-data. We've used bootstrap for the proper styling of the page.
fileform.jsp:
HTML
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>File uploader</title>
</head>
<body>
<h1>Upload File</h1>
<form action="uploadfile" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="formFile" class="form-label">Upload Your file</label>
<input name="thisfile" class="form-control" type="file" id="formFile">
</div>
<button class="btn btn-secondary">Upload</button>
</form>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
The showupload.jsp page displays the uploaded image using jsp to map the image URL.
showupload.jsp:
HTML
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://www.oracle.com/technetwork/java/index.html" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>File Uploaded</h1>
<img src="<c:url value="resources/image/${imgName}"/>"/>
</body>
</html>
Note: After adding all the classes and configuration file, the project structure should look something like this:
Note: Before running the application, you need to manually create a folder named image inside the WEB-INF/resources directory. This folder will be used to store the uploaded files (e.g., images). If the folder does not exist, the application will throw an error when trying to save the uploaded file.
Step 8: Run the Application
Now it's time to run your project, start the Tomcat Server and run your application, now type "http://localhost:8080/SpringMVCFileUpload/upload" in any browser.
Output:
The below image demonstrates a file upload form in a Spring MVC application where users can select and upload a file.
Upload the image and click on upload this will redirect you to the showupload page
Now, you will see your uploaded image.
So we have created a Spring MVC web application with an upload form and displayed the uploaded image on the web.
Similar Reads
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Spring Boot Basics and Prerequisites
Introduction to Spring BootSpring is one of the most popular frameworks for building enterprise applications, but traditional Spring projects require heavy XML configuration, making them complex for beginners.Spring Boot solves this problem by providing a ready-to-use, production-grade framework on top of Spring. It eliminate
4 min read
Difference between Spring and Spring BootSpring Spring is an open-source lightweight framework that allows Java developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier
4 min read
Spring - Understanding Inversion of Control with ExampleSpring IoC (Inversion of Control) Container is the core of the Spring Framework. It creates and manages objects (beans), injects dependencies and manages their life cycles. It uses Dependency Injection (DI), based on configurations from XML files, Java-based configuration, annotations or POJOs. Sinc
6 min read
Spring - IoC ContainerThe Spring framework is a powerful framework for building Java applications. It can be considered a collection of sub-frameworks, also referred to as layers, such as Spring AOP, Spring ORM, Spring Web Flow, and Spring Web MVC. We can use any of these modules separately while constructing a Web appli
2 min read
BeanFactory vs ApplicationContext in SpringThe Spring Framework provides two core packages that enable Inversion of Control (IoC) and Dependency Injection (DI):org.springframework.beansorg.springframework.contextThese packages define Spring containers that manage the lifecycle and dependencies of beans.Spring offers two main containers1. Bea
6 min read
Spring Boot Core
Spring Boot - ArchitectureSpring Boot is built on top of the Spring Framework and follows a layered architecture. Its primary goal is to simplify application development by providing auto-configuration, embedded servers and a production-ready environment out of the box.The architecture of Spring Boot can be divided into seve
2 min read
Spring Boot - AnnotationsAnnotations in Spring Boot are metadata that simplify configuration and development. Instead of XML, annotations are used to define beans, inject dependencies and create REST endpoints. They reduce boilerplate code and make building applications faster and easier. Core Spring Boot Annotations 1. @Sp
5 min read
Spring Boot ActuatorDeveloping and managing an application are the two most important aspects of the applicationâs life cycle. It is very important to know what is going on beneath the application. Also, when we push the application into production, managing it gradually becomes critically important. Therefore, it is a
5 min read
How to create a basic application in Java Spring BootSpring Boot is the most popular Java framework that is used for developing RESTful web applications. In this article, we will see how to create a basic Spring Boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also p
3 min read
Spring Boot - Code StructureThere is no specific layout or code structure for Spring Boot Projects. However, there are some best practices followed by developers that will help us too. You can divide your project into layers like service layer, entity layer, repository layer,, etc. You can also divide the project into modules.
3 min read
Spring Boot - SchedulingSpring Boot provides the ability to schedule tasks for execution at a given time period with the help of @Scheduled annotation. This article provides a step by step guideline on how we can schedule tasks to run in a spring boot application Implementation:It is depicted below stepwise as follows:Â St
4 min read
Spring Boot - LoggingLogging in Spring Boot plays a vital role in Spring Boot applications for recording information, actions, and events within the app. It is also used for monitoring the performance of an application, understanding the behavior of the application, and recognizing the issues within the application. Spr
8 min read
Exception Handling in Spring BootException handling in Spring Boot helps deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Key Approaches
8 min read
Spring Boot with REST API
Spring Boot - Introduction to RESTful Web ServicesRESTful Web Services REST stands for REpresentational State Transfer. It was developed by Roy Thomas Fielding, one of the principal authors of the web protocol HTTP. Consequently, REST was an architectural approach designed to make the optimum use of the HTTP protocol. It uses the concepts and verbs
5 min read
Spring Boot - REST ExampleIn modern web development, most applications follow the Client-Server Architecture. The Client (frontend) interacts with the server (backend) to fetch or save data. This communication happens using the HTTP protocol. On the server, we expose a bunch of services that are accessible via the HTTP proto
4 min read
How to Create a REST API using Java Spring Boot?Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
How to Make a Simple RestController in Spring Boot?A RestController in Spring Boot is a specialized controller that is used to develop RESTful web services. It is marked with the @RestController annotation, which combines @Controller and @ResponseBody. This ensures that the response is automatically converted into JSON or XML, eliminating the need f
2 min read
JSON using Jackson in REST API Implementation with Spring BootWhen we build REST APIs with Spring Boot, we need to exclude NULL values from the JSON responses. This is useful when we want to optimize the data being transferred, making the response more compact and easier to process for the client.In this article, we are going to learn the approach that is used
4 min read
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot Kafka Producer ExampleSpring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Spring Boot Kafka Consumer ExampleSpring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Spring Boot | How to consume JSON messages using Apache KafkaApache Kafka is a stream processing system that lets you send messages between processes, applications, and servers. In this article, we will see how to publish JSON messages on the console of a Spring boot application using Apache Kafka. In order to learn how to create a Spring Boot project, refer
3 min read
Spring Boot | How to consume string messages using Apache KafkaApache Kafka is a publish-subscribe messaging queue used for real-time streams of data. A messaging queue lets you send messages between processes, applications, and servers. In this article we will see how to send string messages from apache kafka to the console of a spring boot application. Appro
3 min read
Spring Boot | How to publish String messages on Apache KafkaApache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send string messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, r
2 min read
Spring Boot | How to publish JSON messages on Apache KafkaApache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send JSON messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, ref
4 min read
Spring Boot with AOP
Spring Boot - AOP(Aspect Oriented Programming)The Java applications are developed in multiple layers, to increase security, separate business logic, persistence logic, etc. A typical Java application has three layers namely they are Web layer, the Business layer, and the Data layer. Web layer: This layer is used to provide the services to the e
4 min read
How to Implement AOP in Spring Boot Application?AOP(Aspect Oriented Programming) breaks the full program into different smaller units. In numerous situations, we need to log, and audit the details as well as need to pay importance to declarative transactions, security, caching, etc., Let us see the key terminologies of AOP Aspect: It has a set of
10 min read
Spring Boot - Difference Between AOP and OOPAOP(Aspect-Oriented Programming) complements OOP by enabling modularity of cross-cutting concerns. The Key unit of Modularity(breaking of code into different modules) in Aspect-Oriented Programming is Aspect. one of the major advantages of AOP is that it allows developers to concentrate on business
3 min read
Spring Boot - Difference Between AOP and AspectJSpring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
3 min read
Spring Boot - Cache ProviderThe Spring Framework provides support for transparently adding caching to an application. The Cache provider gives authorization to programmers to configure cache explicitly in an application. It incorporates various cache providers such as EhCache, Redis, Guava, Caffeine, etc. It keeps frequently a
6 min read