#IT star is not a dream # [0] to start real development Web development SpringBoot Multipart upload and download files

table of Contents:

A, SpringBoot configuration Multipart

Second, the package file operation FileHelper.java

Third, upload and download API development FileController.java

Four, unit testing FileControllerTest.java

V. Extension

Six, common problems and solutions


Open source projects: https://github.com/jextop/StarterApi


SpringBoot is commonly used when the Java development framework, has a very rich set of components and ease of use features. Multipart used to support clients to upload files to the server, the server gets the request from the contents of the file stream, saved to local or cloud. The system architecture diagram as follows:

image.png

The main classes and interfaces related as follows:

image.png

Development steps:


Code file

Function Points

SpringBoot configuration Multipart

application.yml

SpringBoot Web dependence has been introduced, arranged in a multipart application.yml

ServerConfig.java

Reads the service address, url splicing

MultipartConfig.java

Reads the local storage address, save the file

File Operations

FileHelper.java

Read and write files, as well as auxiliary functions

API development

FileController.java

增加REST接口POST /upload/{file}, GET /download/{name}

单元测试

FileControllerTest.java

测试功能,MockHttpServletResponse, MockMultipartFile

功能扩展

集成DB读写功能,建立数据表File

在数据库中存储文件名称,MD5等信息,上传时判断MD5一样就重用,下载时返回源文件名。

FileTypeEnum.java

声明文件类型,归类存储

LocationEnum.java

支持本地或云端存储,比如阿里云、七牛云


一,SpringBoot配置Multipart

1. SpringBoot Web项目,已经包含了Multipart依赖,需要在application.yml中配置如下,开启multipart功能,指定文件大小范围和存储路径:

spring:
  servlet:
    multipart:
      enabled: true
      location: files
      file-size-threshold: 0B
      max-file-size: 10MB
      max-request-size: 10MB

2. 配置ServerConfig,读取API服务的IP地址或者域名,在返回文件信息时拼接url。

3. 配置MultipartConfig,读取文件存储路径,FileHelper写入文件时使用。


二,封装文件操作

文件读写,生成存储路径和网络url,实现代码详见FileHelper.java

1. save()将MultipartFile文件流保存到服务器或云端。

2. read()将文件内容读出并写如HttpServletResponse中。

3. getFilePath()得到文件存储路径。

4. getFileUrl()得到访问文件的网络url


三,上传下载API开发FileController.java

增加两个REST接口,上传接口/file/upload是POST请求,处理单个或者多个文件;下载接口/file/download/{name}是GET请求,name是根据文件唯一编号+扩展名生成的名称。实现代码详见FileController.java

@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
    public Object upload(
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam(value = "files", required = false) MultipartFile[] files
    ) {
        if (file != null) {
            LogUtil.info("/file/upload", file.getName());
        }

        if (!EmptyUtil.isEmpty(files)) {
            LogUtil.info("/file/upload", files.length);
        }
    }

    @GetMapping("/{name}")
    public Object download(HttpServletResponse response, @PathVariable("name") String name) {
        LogUtil.info("/file", name);
    }
}

1,文件上传时首先根据内容生成MD5,通过MD5判断文件是否重复,然后保存文件并记录信息到数据库,返回文件url,时序图如下。


问答:为什么要保存文件信息到数据库?

- 首先将文件MD5保存起来,可以有效的避免文件重复。

- 存储在服务器时,文件名称使用一个新生成的唯一编号,这个编号也是url关键字。

- 文件原名保存到数据库,下载时可以返回给客户端。

image.png

2,下载文件时,从请求参数中获取文件编号,根据服务器存储路径查找文件。通过根据文件编号在数据库中查询并返回信息,流程图如下。

image.png

四,单元测试FileControllerTest.java

Spring框架提供了Mock功能辅助测试HTTP,我们用到org.springframework.mock.web包中的两个类:MockMultipartFile在上传时模拟文件,MockHttpServletResponse在下载时模拟HttpResponse响应。

1,创建一个临时文件,然后构建一个MockMultipartFile,测试upload()函数时传入。

File file = File.createTempFile("tmp", ".txt");
FileUtil.write(file.getPath(), "tmp file".getBytes());


MockMultipartFile multipart = new MockMultipartFile(
        file.getName(), file.getName(), null,
        new FileInputStream(file)
);

Object ret = fileController.doUpload(multipart, null);

2,新建一个MockHttpServletResponse实例,传入download()函数,将下载文件内容写入Response。

HttpServletResponse response = new MockHttpServletResponse();
Object ret = fileController.download(response, f200216377344237183100944.jpg);

3,运行FileControllerTest.java,,测试结果:

image.png

五,功能扩展

1. 存储文件时,将文件信息和MD5存入数据库,MD5用于检查重复文件,文件原名称等信息在下载时返回。

2. 文件存储时使用新生成的唯一编号作为文件名称,编号也是网络url关键字。

3. 文件存储可以扩展到云端,比如阿里云、七牛云,在FileController的upload()和download()函数流程中切换。


六,常见问题和解决方法

如何高效率的调试REST接口?

解决:有多种方法和API调式工具可用,介绍3个方式:

1, unit testing: introduced above, the Spring Framework provides a secondary HTTP Mock functional testing, unit testing functions covering the main functions, and automatic construction system, and integration, and can find the bug codes and functional defects caused by changes, the quality assurance program.

image.png

2, Swagger interface documentation and call: Swagger framework defines a complete REST interface documentation specification, provides a powerful page testing capabilities, the ability to debug and visualization API interface services, and the integration of documents into the code, allowing maintenance documentation and modify the code integration as a whole, such that the modified code logic while easily modify documentation.


Browser to open http: // localhost: 8011 / swagger -ui.html, expansion interface information, select the file and then " the Try IT ou! "

image.png

3, Postman is a common API debugging tools, support a variety of ways and request configuration environment variable, and returns the results of test verification, support for batch automation running, you can automatically build and system integration, and can import and export JSON file, efficient team cooperation.

image.png

Guess you like

Origin blog.51cto.com/13851865/2471526