Upload Multiple Files in Spring Boot using JPA, Thymeleaf, Multipart
Last Updated :
06 Feb, 2023
Spring 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 setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. In this article, we will learn how to upload multiple files to the server with the help of Spring boot. So to make it successful we will use MySQL as a database, Thymeleaf as a template engine, and JPA to save the data in the Database.
Step by Step Process
Step 1: So first we will set up the spring project in STS(Spring tool suite) IDE. Whose instructions have been given below.
- Click File -> New -> Project -> Select Spring Starter Project -> Click Next.
- New Dialog box will open where you will provide the project-related information like project name, Java version, Maven version, and so on.
- After that select required maven dependencies like MySQL Driver (for the database), Spring Data JPA, Spring Web, Thymeleaf, Spring Boot DevTools for (Provides fast application restarts, LiveReload, and configurations for enhanced development experience.)
- Click Finish.
Step 2: After build, we have to create a package structure for all Java files like this. Here our project name is FileUpload.

Step 3: Let’s begin with the coding
application.properties file:
# It means server will run on port 8080
server.port=8080
# connection url
spring.datasource.url=jdbc:mysql://localhost:3306/filedb
# DB user
spring.datasource.username=root
# DB password
spring.datasource.password=[Your Password]
# update the schema
spring.jpa.hibernate.ddl-auto=update
# translate its generic SQL statements into vendor specific DDL, DML
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
# off to show SQL query
spring.jpa.show-sql=false
Note: Before setting up the application.properties file, make sure that you have created the schema in your database.
Through MySql workbench.
Through MySql command line.
- Open Mysql command line.
- Run create database filedb; and hit enter.
FileModal.java
Let’s write a simple POJO class that will serve as input and output to our web service methods.
Java
package com.example.user.modal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
@Table (name = "filemodal" )
public class FileModal {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column (name = "id" )
long id;
@Column (name = "name" )
String fileName;
@Lob
@Column (name = "content" )
String content;
@Column (name = "filetype" )
private String fileType;
public FileModal() {
super ();
}
public FileModal(String fileName, String content, String fileType) {
super ();
this .fileName = fileName;
this .content = content;
this .fileType = fileType;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this .fileName = fileName;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this .content = content;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this .fileType = fileType;
}
}
|
FileRepository.java
FileRepository.java extends the JpaRepository interface for DB operations.
Java
package com.example.user.repoasitory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.user.modal.FileModal;
@Repository
public interface FileRepository extends JpaRepository<FileModal, Long> {
}
|
FileService.java
FileService.java interface which contain two abstract methods getAllFiles() and saveAllFilesList(List<FileModal> fileList).
Java
package com.example.user.service;
import java.util.List;
import com.example.user.modal.FileModal;
public interface FileService {
List<FileModal> getAllFiles();
void saveAllFilesList(List<FileModal> fileList);
}
|
FileServiceImplementation.java
FileServiceImplementation.java class which implements the FileService.java interface and provides the definition of the abstract methods.
Java
package com.example.user.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.user.modal.FileModal;
import com.example.user.repoasitory.FileRepository;
@Service
public class FileServiceImplementation implements FileService {
@Autowired
FileRepository fileRepository;
@Override
public List<FileModal> getAllFiles() {
return fileRepository.findAll();
}
public void saveAllFilesList(List<FileModal> fileList) {
for (FileModal fileModal : fileList)
fileRepository.save(fileModal);
}
}
|
FileController.java
This FileController.java class receives inputs from the users via the View, then processes the user’s data with the help of Model and passes the results back to the View. So here the user will upload files from the UI, They will be received as a multipart array in the respective method.
Java
package com.example.user.controller;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.MultipartFile;
import com.example.user.modal.FileModal;
import com.example.user.service.FileServiceImplementation;
@Controller
public class FileController {
@Autowired
FileServiceImplementation fileServiceImplementation;
@GetMapping ( "/" )
public String getData() {
return "File" ;
}
@PostMapping ( "/" )
public String uploadMultipartFile( @RequestParam ( "files" ) MultipartFile[] files, Model modal) {
try {
List<FileModal> fileList = new ArrayList<FileModal>();
for (MultipartFile file : files) {
String fileContentType = file.getContentType();
String sourceFileContent = new String(file.getBytes(), StandardCharsets.UTF_8);
String fileName = file.getOriginalFilename();
FileModal fileModal = new FileModal(fileName, sourceFileContent, fileContentType);
fileList.add(fileModal);
}
fileServiceImplementation.saveAllFilesList(fileList);
} catch (Exception e) {
e.printStackTrace();
}
modal.addAttribute( "allFiles" , fileServiceImplementation.getAllFiles());
return "FileList" ;
}
}
|
FileApplication.java
This is the main class from where spring applications are ready to run.
Java
package com.example.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FileApplication {
public static void main(String[] args) {
SpringApplication.run(FileApplication. class , args);
}
}
|
File.html
So here in this HTML file <input type=”file”> accepts a single file. You can allow multiple files via <input type=”file” multiple> and webkitdirectory switches the browser’s file picker to select a directory. All files inside that directory, and inside any nested subdirectories, will be selected for the file input. and enctype=’multipart/form-data is an encoding type that allows files to be sent through a POST. Quite simply, without this encoding, the files cannot be sent through POST. If you want to allow a user to upload a file via a form, you must use this enctype.
HTML
<!DOCTYPE html>
< html >
< head >
< meta charset = "ISO-8859-1" >
< title >File Upload</ title >
</ head >
< style >
input[type=file], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
background-color: #1affff;
}
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-left: 45%;
cursor: pointer;
}
.button4 {
border-radius: 10px;
}
div {
border-radius: 5px;
background-color: #a6a6a6;
padding: 10px;
width: 50%;
margin: auto;
}
</ style >
< body >
< form method = "POST" enctype = "multipart/form-data" >
< div >< div >
< input type = "file" name = "files"
webkitdirectory multiple></ div >
< button class = "button button4" type = "submit" >
Upload</ button > </ div >
</ form >
</ body >
</ html >
|
FileList.html
So here in this HTML file, we simply print the file-related data using thymeleaf loop.
<tr th:each="file: ${allFiles}">
<td th:text="${file.fileName}"></td>
<td th:text="${file.fileType}"></td>
</tr>
This is the thymeleaf loop to iterate all items of allFiles list which is coming from the Java controller via modal.addAttribute(“allFiles”, fileServiceImplementation.getAllFiles()); method in the form of key-value pair.
- th:each=”file: ${allFiles}” -> Assigning the FileModal into file name variable one by one.
- th:text=”${file.fileName}” -> Here you access the fileName field which you have written in FileModal Pojo.
- th:text=”${file.fileType}” -> Here you access the fileType field which you have written in FileModal Pojo.
HTML
<!DOCTYPE html>
< head >
< title >All files</ title >
< meta charset = "utf-8" />
< meta name = "viewport" content = "width=device-width, initial-scale=1" />
4.1.0/css/bootstrap.min.css">
jquery.min.js"></ script >
umd/popper.min.js"></ script >
bootstrap.min.js"></ script >
</ head >
< body >
< div class = "container h-100" >
< div class = "row h-100 justify-content-center align-items-center" >
< div class = "col-md-7 table-responsive" >
< h2 >Uploaded Files</ h2 >
< table id = "customerTable" class = "table" >
< thead >
< tr >
< th >File Name</ th >
< th >File Type</ th >
</ tr >
</ thead >
< tbody >
< tr th:each = "file: ${allFiles}" >
< td th:text = "${file.fileName}" ></ td >
< td th:text = "${file.fileType}" ></ td >
</ tr >
</ tbody >
</ table >
< hr >
< div >
< a href = "/" class = "btn btn-light btn-block"
role = "button" >Back to Upload Form</ a >
</ div >
</ div >
</ div >
</ div >
</ body >
</ html >
|
So when you complete all the above steps. then simply run your application as spring boot.
- Right-click on your project -> Run as -> Spring boot app
- Open your browser and type localhost:8080/ in URL and hit enter.
Output:
Similar Reads
Spring Boot - AOP Before Advice
Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns such as transa
4 min read
Spring Boot - DevTools
Spring Boot provides DevTools, a module designed to ease your development process, it improves the experience of developing applications resulting in optimizing the developer's productivity for building exceptional software. It aims to reduce development time, by intelligently detecting code changes
5 min read
Spring Boot - Dependency Management
Spring Boot framework is the most popular web development framework. No doubt, it provides an abundance of essential features and a convenient way to handle those features. At the heart of Spring Boot is the 'Dependency Management' feature. Importance of Dependency ManagementCentralized Dependency M
6 min read
Spring Boot - Caching
Spring Boot is a project that is built on top of the Spring Framework that provides an easier and faster way to set up, configure, and run both simple and web-based applications. It is one of the popular frameworks among developers these days because of its rapid production-ready environment which e
6 min read
Spring Boot - Starter Web
Today most of the applications demand Model-View-Controller (MVC) architecture to meet the various needs like handling user data, making application efficient, to provide dynamic nature to applications. It was basically used for building desktop graphical user interfaces (GUIs), but now is becoming
6 min read
Spring Boot - Difference Between @Service Annotation and @Repository Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. @Service Annotat
7 min read
Unit Testing in Spring Boot Project using Mockito and Junit
Spring 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
6 min read
Spring Boot - Thymeleaf with Example
Thymeleaf is a server-side Java-based template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. It is more powerful than JPS and responsible for dynamic content rendering on UI. The engine allows a parallel work of the backend and
6 min read
Spring Boot - MongoRepository with Example
Spring 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
5 min read
Spring Boot - Integrating Hibernate and JPA
Spring 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