Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 annotation defines that a
// class can be mapped to a table
@Entity  
 
// @Table annotation defines name of the table
@Table(name = "filemodal")
public class FileModal {
    // @Id annotation specifies the
    // primary key of an entity
    @Id 
   
    // @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;
    @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 annotation is used to
// indicate that the class provides the mechanism
// for storage, retrieval, search,update and delete
// operation on objects.
@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 annotation is used with classes
// that provide some business functionalities
@Service
public class FileServiceImplementation implements FileService {
 
    // @Autowired annotation used to inject
    // the object dependency of FileRepository
    @Autowired 
    FileRepository fileRepository;
   
    @Override
    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)
            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 annotation is used to
// mark any java class as a controller class
@Controller 
public class FileController {
 
    @Autowired
    FileServiceImplementation fileServiceImplementation;
 
    // @GetMapping annotation for
    // mapping HTTP GET requests onto
    // specific handler methods. */
    @GetMapping("/")
    public String getData() {
        return "File";
    }
   
    // @PostMapping annotation maps HTTP POST
    // requests onto specific handler methods
    @PostMapping("/")
    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
            fileList.add(fileModal);
            }
       
            // Saving all the list item into database
            fileServiceImplementation.saveAllFilesList(fileList);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
       
        // 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";
    }
}


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;
 
// 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
@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>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>All files</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/
      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:



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