Open In App
Related Articles

Upload Multiple Files in Spring Boot using JPA, Thymeleaf, Multipart

Like Article
Save Article
Report issue

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 file:

# It means server will run on port 8080

# connection url
# DB user  

# DB password
spring.datasource.password=[Your Password]  
# update the schema

# translate its generic SQL statements into vendor specific DDL, DML   
# off to show SQL query 

Note: Before setting up the 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.

Let’s write a simple POJO class that will serve as input and output to our web service methods.


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 annotation defines that a
// class can be mapped to a table
// @Table annotation defines name of the table
@Table(name = "filemodal")
public class FileModal {
    // @Id annotation specifies the
    // primary key of an entity
    // @GeneratedValue annotation Provides for the
    // specification of generation strategies
    // for the values of primary keys
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    // @Column annotation specifies
    // the name of the column
    @Column(name = "id")
    long id;
    @Column(name = "name")
    String fileName;
    @Column(name = "content")
    String content;
    @Column(name = "filetype")
    private String fileType;
    public FileModal() {
    public FileModal(String fileName, String content, String fileType) {
        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;

             extends the JpaRepository interface for DB operations.


package com.example.user.repoasitory;
import org.springframework.stereotype.Repository;
import com.example.user.modal.FileModal;
// @Repository annotation is used to
// indicate that the class provides the mechanism
// for storage, retrieval, search,update and delete
// operation on objects.
public interface FileRepository extends JpaRepository<FileModal, Long> {

             interface which contain two abstract methods getAllFiles() and saveAllFilesList(List<FileModal> fileList).


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);

             class which implements the interface and provides the definition of the abstract methods. 


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 annotation is used with classes
// that provide some business functionalities
public class FileServiceImplementation implements FileService {
    // @Autowired annotation used to inject
    // the object dependency of FileRepository
    FileRepository fileRepository;
    public List<FileModal> getAllFiles() {
        // fetch all the files form database
        return fileRepository.findAll();
    public void saveAllFilesList(List<FileModal> fileList) {
        // Save all the files into database
        for (FileModal fileModal : fileList)


This 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. 


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 annotation is used to
// mark any java class as a controller class
public class FileController {
    FileServiceImplementation fileServiceImplementation;
    // @GetMapping annotation for
    // mapping HTTP GET requests onto
    // specific handler methods. */
    public String getData() {
        return "File";
    // @PostMapping annotation maps HTTP POST
    // requests onto specific handler methods
    public String uploadMultipartFile(@RequestParam("files") MultipartFile[] files, Model modal) {
    try {
        // Declare empty list for collect the files data
        // which will come from UI
        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);
            // Adding file into fileList
            // Saving all the list item into database
        } catch (Exception e) {
        // Send file list to View using modal class   
        // fileServiceImplementation.getAllFiles() used to
        // fetch all file list from DB
        modal.addAttribute("allFiles", fileServiceImplementation.getAllFiles());
        return "FileList";


This is the main class from where spring applications are ready to run.


package com.example.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// Spring Boot @SpringBootApplication annotation is used to mark a configuration
// class that declares one or more @Bean methods and also triggers auto-configuration
// and component scanning. It’s the same as declaring a class with @Configuration,
// @EnableAutoConfiguration and @ComponentScan annotations
public class FileApplication {
    public static void main(String[] args) {, args);



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.


<!DOCTYPE html>
<meta charset="ISO-8859-1">
<title>File Upload</title>
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;
    <form method="POST" enctype="multipart/form-data">
            <input type="file" name="files"
             webkitdirectory multiple></div>
            <button class="button button4" type="submit">
             Upload</button> </div>



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>

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.


<!DOCTYPE html>
<html lang="en" xmlns:th="">
<title>All files</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet"href="
    <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">
                <th>File Name</th>
                <th>File Type</th>
            <tr th:each="file: ${allFiles}">
                <td th:text="${file.fileName}"></td>
                <td th:text="${file.fileType}"></td>
         <a href="/" class="btn btn-light btn-block"
           role="button">Back to Upload Form</a>


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.


Last Updated : 06 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads