📜  在 Spring Boot 中使用 JPA、Thymeleaf、Multipart 上传多个文件

📅  最后修改于: 2022-05-13 01:54:55.893000             🧑  作者: Mango

在 Spring Boot 中使用 JPA、Thymeleaf、Multipart 上传多个文件

Spring Boot 建立在 Spring 之上,包含了 Spring 的所有特性。并且由于其快速的生产就绪环境使开发人员能够直接专注于逻辑而不是为配置和设置而苦苦挣扎,如今它正成为开发人员的最爱。 Spring Boot 是一个基于微服务的框架,在其中制作可用于生产的应用程序只需要很少的时间。在本文中,我们将学习如何借助 Spring Boot 将多个文件上传到服务器。所以为了让它成功,我们将使用 MySQL 作为数据库,Thymeleaf 作为模板引擎,并使用 JPA 将数据保存在数据库中。

一步一步的过程

步骤 1:首先我们将在 STS(Spring tool suite) IDE 中设置 spring 项目。下面给出了谁的指示。

  • 单击文件->新建->项目->选择 Spring Starter 项目-> 单击下一步。
  • 新建对话框将打开,您将在其中提供项目相关信息,如项目名称、 Java版本、Maven 版本等。
  • 之后选择所需的maven依赖项,如MySQL 驱动程序(用于数据库)、 Spring Data JPA、Spring Web、Thymeleaf、Spring Boot DevTools (提供快速应用程序重启、LiveReload 和配置以增强开发体验。)
  • 单击完成

第 2 步:构建后,我们必须像这样为所有Java文件创建一个包结构。这里我们的项目名称是FileUpload

第 3 步:让我们从编码开始

application.properties 文件:

# 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 

通过MySql 工作台。

通过MySql 命令行

  • 打开 Mysql 命令行。
  • 运行创建数据库filedb ;然后按回车。

文件模式。Java

让我们编写一个简单的 POJO 类,作为 Web 服务方法的输入和输出。

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


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 {
 
}


Java
package com.example.user.service;
 
import java.util.List;
import com.example.user.modal.FileModal;
 
public interface FileService {
    List getAllFiles();
    void saveAllFilesList(List fileList);
}


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 getAllFiles() {
        // fetch all the files form database
        return fileRepository.findAll();
    }
    public void saveAllFilesList(List fileList) {
        // Save all the files into database
        for (FileModal fileModal : fileList)
            fileRepository.save(fileModal);
    }
}


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 fileList = new ArrayList();
        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";
    }
}


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


HTML




File Upload

 


    
        
            
            
    


HTML



All files







 

    
    
    
    

Uploaded Files

                                                                                                                                                     
File NameFile Type
    
    
         Back to Upload Form     
    
    
    


文件存储库。Java

文件存储库。 Java为 DB 操作扩展了JpaRepository接口。

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 {
 
}

文件服务。Java

文件服务。 Java接口,其中包含两个抽象方法getAllFiles()saveAllFilesList(List fileList)。

Java

package com.example.user.service;
 
import java.util.List;
import com.example.user.modal.FileModal;
 
public interface FileService {
    List getAllFiles();
    void saveAllFilesList(List fileList);
}

文件服务实现。Java

文件服务实现。实现FileServiceJava类。 Java接口并提供抽象方法的定义。

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 getAllFiles() {
        // fetch all the files form database
        return fileRepository.findAll();
    }
    public void saveAllFilesList(List fileList) {
        // Save all the files into database
        for (FileModal fileModal : fileList)
            fileRepository.save(fileModal);
    }
}

文件控制器。Java

这个文件控制器。 Java类通过 View 接收用户的输入,然后在 Model 的帮助下处理用户的数据,并将结果传递回 View。所以在这里用户将从 UI 上传文件,它们将在各自的方法中作为多部分数组接收。

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 fileList = new ArrayList();
        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";
    }
}

文件应用程序。Java

这是准备运行 Spring 应用程序的主要类。

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

文件.html

所以在这个 HTML 文件中, 接受一个文件。您可以通过允许多个文件,并且webkitdirectory 会切换浏览器的文件选择器来选择一个目录。该目录内以及任何嵌套子目录内的所有文件都将被选择用于文件输入。 enctype='multipart/form-data是一种编码类型,允许通过 POST 发送文件。很简单,没有这种编码,文件就不能通过 POST 发送。如果您想允许用户通过表单上传文件,则必须使用此enctype

HTML





File Upload

 


    
        
            
            
    

文件列表.html

所以在这个 HTML 文件中,我们简单地使用 thymeleaf 循环打印文件相关数据。


       
       

这是通过 modal.addAttribute(“allFiles”, fileServiceImplementation.getAllFiles()); 迭代来自Java控制器的 allFiles 列表的所有项目的 thymeleaf 循环。键值对的from中的方法。

  • th:each=”file: ${allFiles}” -> 将FileModal一个一个赋值给文件名变量。
  • th:text=”${file.fileName}” -> 在这里您可以访问您在FileModal Pojo 中编写的文件名字段。
  • th:text=”${file.fileType}” -> 在这里您可以访问您在FileModal Pojo 中编写的 fileType 字段。

HTML




All files







 

    
    
    
    

Uploaded Files

                                                                                                                                                     
File NameFile Type
    
    
         Back to Upload Form     
    
    
    

因此,当您完成上述所有步骤时。然后只需将您的应用程序作为弹簧启动运行。

  • 右键单击您的项目 ->运行方式-> Spring Boot 应用程序
  • 打开浏览器并在 URL 中输入localhost:8080/并按 Enter。

输出: