Implementation and optimization of SpringBoot upload files

1. What is file upload?

File upload refers to the process in which the client sends a local file to the server through the HTTP protocol. File upload is one of the common functions in web development. For example, users can upload various types of files such as avatars, photos, videos, and documents. File upload involves the interaction between the client and the server, and various factors such as file size, format, security, and storage method need to be considered.

2. How to use SpringBoot to implement file upload?

SpringBoot is a lightweight and fast-developing technology based on the Spring framework. It provides many convenient functions, including file upload. SpringBoot uses the FileUpload component to implement file upload processing, and the MultipartFile class can be used in the controller to receive it. The MultipartFile class encapsulates the relevant information of uploaded files, such as file name, file type, file size, file content, etc.

To use SpringBoot to implement file upload, the following steps are required:

  • Add spring-boot-starter-web and spring-boot-starter-thymeleaf dependencies to the pom.xml file to support web development and template engines respectively.
  • Configure parameters related to file upload in the application.yml or application.properties file, such as maximum file size, maximum request size, temporary directory, etc.
  • Define a method in the controller class and use the @RequestParam annotation to receive a parameter of type MultipartFile, representing the uploaded file. In the method, methods of the MultipartFile class can be called to obtain and process the information of the uploaded file, such as getOriginalFilename(), getContentType(), getSize(), transferTo(), and so on.
  • Create an HTML page in the view layer (under the templates directory), use the <form> tag to define a form, and set the method attribute to post and the enctype attribute to multipart/form-data. Use the <input> tag in the form to create an input box with the type attribute as file, which is used to select the file to be uploaded. Set the action attribute to the mapping path of the controller method.
  • Run the SpringBoot application, visit the HTML page, select the file to upload, and click the submit button. At this point, the browser will send the form data and file data to the server, and the server will call the corresponding controller method to receive and process the uploaded file.

The following is a simple example that demonstrates how to use SpringBoot to implement a basic file upload function:

// pom.xml
<dependencies>
    <!-- web依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- thymeleaf依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

// application.yml
spring:
  servlet:
    multipart:
      enabled: true # 启用http上传
      max-file-size: 10MB # 设置支持的单个上传文件的大小限制
      max-request-size: 20MB # 设置最大的请求的文件大小,设置总体大小请求
      file-size-threshold: 512KB # 当上传文件达到指定配置量的时候会将文件内容写入磁盘
      location: / # 设置上传的临时目录

// FileController.java
@Controller
public class FileController {

    // 访问/upload页面显示upload.html页面
    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    // 处理/upload请求,接收并保存上传的文件
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "请选择要上传的文件";
        }
        // 获取原始文件名
        String fileName = file.getOriginalFilename();
        // 获取文件类型
        String contentType = file.getContentType();
        // 获取文件大小
        long size = file.getSize();
        // 生成一个新的文件名,避免重复
        String newFileName = UUID.randomUUID() + "." + contentType.substring(contentType.lastIndexOf("/") + 1);
        // 创建一个文件对象,表示要保存的文件
        File dest = new File("D:/upload/" + newFileName);
        try {
            // 将上传的文件内容写入到目标文件中
            file.transferTo(dest);
            return "上传成功,文件名:" + fileName + ",文件类型:" + contentType + ",文件大小:" + size + ",新文件名:" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败,发生异常:" + e.getMessage();
        }
    }
}

// upload.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <form th:action="@{/upload}" method="post" enctype="multipart/form-data">
        选择要上传的文件:<input type="file" name="file"><br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

3. How to optimize the function and performance of file upload?

The above example only implements the most basic file upload function, but in actual project development, many other factors need to be considered, such as:

  • How to restrict the format and size of uploaded files to prevent users from uploading illegal or oversized files?
  • How to check the security of uploaded files to prevent users from uploading malicious or virus files?
  • How to compress and convert uploaded files to reduce storage space and network transmission overhead?
  • How to perform distributed storage on uploaded files to improve storage capacity and access speed?
  • How to resume the uploaded file and upload in pieces to improve the upload efficiency and user experience?

In response to these problems, we can adopt the following methods to optimize the function and performance of file upload:

  • Use the configuration parameters provided by SpringBoot or custom beans to set the maximum file upload size, maximum request size, temporary directory and other parameters, or use interceptors or filters to preprocess requests, and reject or reject requests that do not meet the requirements. hint.
  • Use third-party tools or libraries to scan and filter uploaded files for security, such as using Apache Tika to detect file types, and ClamAV to detect viruses, etc.
  • Use third-party tools or libraries to compress and convert uploaded files, such as using Thumbnailator to generate thumbnails, and FFmpeg to convert video formats, etc.
  • Use third-party services or platforms for distributed storage of uploaded files, such as FastDFS, HDFS, OSS, etc.
  • Use third-party tools or libraries to perform resuming and multipart uploads of uploaded files, such as WebUploader, Plupload, etc.

The following is a simple example that demonstrates how to implement distributed storage using FastDFS:

@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
        return "请选择要上传的文件";
    }
    // 获取原始文件名
    String fileName = file.getOriginalFilename();
    // 获取文件类型
    String contentType = file.getContentType();
    // 获取文件大小
    long size = file.getSize();
    // 生成一个新的文件名,避免重复
    String newFileName = UUID.randomUUID() + "." + contentType.substring(contentType.lastIndexOf("/") + 1);
    // 创建一个文件对象,表示要保存的文件
    File dest = new File("D:/upload/" + newFileName);
    try {
        // 将上传的文件内容写入到目标文件中
        file.transferTo(dest);
        return "上传成功,文件名:" + fileName + ",文件类型:" + contentType + ",文件大小:" + size + ",新文件名:" + newFileName;
    } catch (IOException e) {
        e.printStackTrace();
        return "上传失败,发生异常:" + e.getMessage();
    }
}

Guess you like

Origin blog.csdn.net/TaloyerG/article/details/132491167