Spring Boot 与 Docker
观察 GraphQL 的实际运行

本指南将引导您创建一个能够接收HTTP多部分文件上传的服务器应用程序。

你将构建什么

您将创建一个能够接受文件上传的 Spring Boot Web 应用程序。您还将构建一个简单的 HTML 界面来上传测试文件。

所需准备

如何完成本指南

与大多数 Spring 入门指南一样,您可以从头开始并完成每个步骤,或者可以跳过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会得到可运行的代码。

从头开始,请继续阅读 从 Spring Initializr 开始

跳过基础部分,请执行以下操作:

完成后,您可以通过 gs-uploading-files/complete 中的代码来检查您的结果。

从 Spring Initializr 开始

您可以使用这个预初始化项目,然后点击生成以下载一个 ZIP 文件。该项目已配置为适应本教程中的示例。

要手动初始化项目:

  1. 访问 https://start.spring.io。该服务会为您拉取应用程序所需的所有依赖项,并完成大部分设置工作。

  2. 选择 Gradle 或 Maven 以及您想要使用的语言。本指南假设您选择了 Java。

  3. 点击 Dependencies 并选择 Spring WebThymeleaf

  4. 点击 Generate

  5. 下载生成的 ZIP 文件,这是一个根据您的选择配置好的 Web 应用程序的压缩包。

如果您的 IDE 集成了 Spring Initializr,您可以直接在 IDE 中完成这一过程。

您还可以从 Github 上 fork 该项目,并在您的 IDE 或其他编辑器中打开它。

创建应用程序类

要启动一个 Spring Boot MVC 应用程序,首先需要一个启动器。在这个示例中,spring-boot-starter-thymeleafspring-boot-starter-web 已经被添加为依赖项。为了使用 Servlet 容器上传文件,您需要注册一个 MultipartConfigElement 类(在 web.xml 中相当于 <multipart-config>)。多亏了 Spring Boot,所有内容都会自动为您配置!

开始使用这个应用程序,您只需要以下 UploadingFilesApplication 类(来自 src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java):

package com.example.uploadingfiles;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class UploadingFilesApplication {

    public static void main(String[] args) {
        SpringApplication.run(UploadingFilesApplication.class, args);
    }

}

作为自动配置 Spring MVC 的一部分,Spring Boot 将创建一个 MultipartConfigElement bean,并为文件上传做好准备。

创建文件上传控制器

初始应用程序已经包含了一些类,用于处理在磁盘上存储和加载上传的文件。它们都位于com.example.uploadingfiles.storage包中。您将在新的FileUploadController中使用这些类。下面的代码清单(来自src/main/java/com/example/uploadingfiles/FileUploadController.java)展示了文件上传控制器:

package com.example.uploadingfiles;

import java.io.IOException;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.example.uploadingfiles.storage.StorageFileNotFoundException;
import com.example.uploadingfiles.storage.StorageService;

@Controller
public class FileUploadController {

    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {

        model.addAttribute("files", storageService.loadAll().map(
                path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
                        "serveFile", path.getFileName().toString()).build().toUri().toString())
                .collect(Collectors.toList()));

        return "uploadForm";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = storageService.loadAsResource(filename);

        if (file == null)
            return ResponseEntity.notFound().build();

        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

    @PostMapping("/")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
            RedirectAttributes redirectAttributes) {

        storageService.store(file);
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + file.getOriginalFilename() + "!");

        return "redirect:/";
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }

}

FileUploadController 类被 @Controller 注解标记,以便 Spring MVC 能够识别它并查找路由。每个方法都用 @GetMapping@PostMapping 标记,以将路径和 HTTP 操作绑定到特定的控制器操作。

在这种情况下:

  • GET /: 从 StorageService 中查找当前上传的文件列表,并将其加载到 Thymeleaf 模板中。它使用 MvcUriComponentsBuilder 计算实际资源的链接。

  • GET /files/{filename}: 加载资源(如果存在)并通过 Content-Disposition 响应头将其发送到浏览器以供下载。

  • POST /: 处理多部分消息 file 并将其交给 StorageService 进行保存。

在生产环境中,您更有可能将文件存储在临时位置、数据库或NoSQL存储(例如Mongo的GridFS)中。最好不要用内容加载应用程序的文件系统。

您需要提供一个 StorageService,以便控制器能够与存储层(例如文件系统)进行交互。以下清单(来自 src/main/java/com/example/uploadingfiles/storage/StorageService.java)展示了该接口:

package com.example.uploadingfiles.storage;

import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Path;
import java.util.stream.Stream;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}

您还需要四个类来支持存储服务:

package com.example.uploadingfiles.storage;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("storage")
public class StorageProperties {

    /**
     * Folder location for storing files
     */
    private String location = "upload-dir";

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

}
package com.example.uploadingfiles.storage;

public class StorageException extends RuntimeException {

    public StorageException(String message) {
        super(message);
    }

    public StorageException(String message, Throwable cause) {
        super(message, cause);
    }
}
package com.example.uploadingfiles.storage;

public class StorageFileNotFoundException extends StorageException {

    public StorageFileNotFoundException(String message) {
        super(message);
    }

    public StorageFileNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}
package com.example.uploadingfiles.storage;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileSystemStorageService implements StorageService {

    private final Path rootLocation;

    @Autowired
    public FileSystemStorageService(StorageProperties properties) {

        if(properties.getLocation().trim().length() == 0){
            throw new StorageException("File upload location can not be Empty."); 
        }

        this.rootLocation = Paths.get(properties.getLocation());
    }

    @Override
    public void store(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                throw new StorageException("Failed to store empty file.");
            }
            Path destinationFile = this.rootLocation.resolve(
                    Paths.get(file.getOriginalFilename()))
                    .normalize().toAbsolutePath();
            if (!destinationFile.getParent().equals(this.rootLocation.toAbsolutePath())) {
                // This is a security check
                throw new StorageException(
                        "Cannot store file outside current directory.");
            }
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, destinationFile,
                    StandardCopyOption.REPLACE_EXISTING);
            }
        }
        catch (IOException e) {
            throw new StorageException("Failed to store file.", e);
        }
    }

    @Override
    public Stream<Path> loadAll() {
        try {
            return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(this.rootLocation::relativize);
        }
        catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }

    }

    @Override
    public Path load(String filename) {
        return rootLocation.resolve(filename);
    }

    @Override
    public Resource loadAsResource(String filename) {
        try {
            Path file = load(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            }
            else {
                throw new StorageFileNotFoundException(
                        "Could not read file: " + filename);

            }
        }
        catch (MalformedURLException e) {
            throw new StorageFileNotFoundException("Could not read file: " + filename, e);
        }
    }

    @Override
    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

    @Override
    public void init() {
        try {
            Files.createDirectories(rootLocation);
        }
        catch (IOException e) {
            throw new StorageException("Could not initialize storage", e);
        }
    }
}

创建 HTML 模板

以下 Thymeleaf 模板(来自 src/main/resources/templates/uploadForm.html)展示了如何上传文件并显示已上传内容的示例:

<html xmlns:th="https://www.thymeleaf.org">
<body>

    <div th:if="${message}">
        <h2 th:text="${message}"/>
    </div>

    <div>
        <form method="POST" enctype="multipart/form-data" action="/">
            <table>
                <tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
                <tr><td></td><td><input type="submit" value="Upload" /></td></tr>
            </table>
        </form>
    </div>

    <div>
        <ul>
            <li th:each="file : ${files}">
                <a th:href="${file}" th:text="${file}" />
            </li>
        </ul>
    </div>

</body>
</html>

这个模板包含三个部分:

  • 顶部的一个可选消息区域,Spring MVC 在这里写入闪存作用域的消息

  • 一个允许用户上传文件的表单。

  • 后端提供的文件列表。

调整文件上传限制

在配置文件上传时,通常设置文件大小限制非常有用。想象一下尝试处理一个5GB的文件上传!通过Spring Boot,我们可以使用一些属性设置来调整其自动配置的MultipartConfigElement

将以下属性添加到您现有的属性设置中(在src/main/resources/application.properties中):

spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB

多部分设置的限制如下:

  • spring.servlet.multipart.max-file-size 设置为 128KB,意味着单个文件大小不能超过 128KB。
  • spring.servlet.multipart.max-request-size 设置为 128KB,意味着 multipart/form-data 请求的总大小不能超过 128KB。

更新应用程序

您需要一个目标文件夹来上传文件,因此需要增强 Spring Initializr 创建的基础 UploadingFilesApplication 类,并添加一个 Boot CommandLineRunner,以便在启动时删除并重新创建该文件夹。以下清单(来自 src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java)展示了如何实现这一点:

package com.example.uploadingfiles;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import com.example.uploadingfiles.storage.StorageProperties;
import com.example.uploadingfiles.storage.StorageService;

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class UploadingFilesApplication {

    public static void main(String[] args) {
        SpringApplication.run(UploadingFilesApplication.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}

运行应用程序

@SpringBootApplication 是一个便捷的注解,它添加了以下所有内容:

  • @Configuration: 将该类标记为应用上下文的 bean 定义源。

  • @EnableAutoConfiguration: 告诉 Spring Boot 根据类路径设置、其他 bean 和各种属性设置开始添加 bean。例如,如果类路径上有 spring-webmvc,该注解会将应用程序标记为 Web 应用程序,并激活关键行为,例如设置 DispatcherServlet

  • @ComponentScan: 告诉 Spring 在 com/example 包中查找其他组件、配置和服务,使其能够找到控制器。

main() 方法使用 Spring Boot 的 SpringApplication.run() 方法来启动应用程序。您是否注意到没有一行 XML 代码?也没有 web.xml 文件。这个 Web 应用程序是 100% 纯 Java 的,您不需要处理任何配置管道或基础设施。

构建可执行的 JAR 文件

您可以使用 Gradle 或 Maven 从命令行运行应用程序。您还可以构建一个包含所有必要依赖、类和资源的单一可执行 JAR 文件并运行它。构建可执行 JAR 文件使得在整个开发生命周期中,跨不同环境等场景下,更容易交付、版本控制和部署服务。

如果使用 Gradle,可以通过 ./gradlew bootRun 运行应用程序。或者,您可以使用 ./gradlew build 构建 JAR 文件,然后像下面这样运行 JAR 文件:

java -jar build/libs/gs-uploading-files-0.1.0.jar

如果您使用 Maven,可以通过 ./mvnw spring-boot:run 来运行应用程序。或者,您也可以使用 ./mvnw clean package 构建 JAR 文件,然后按如下方式运行该 JAR 文件:

java -jar target/gs-uploading-files-0.1.0.jar

这里描述的步骤创建一个可运行的 JAR 文件。您也可以构建一个经典的 WAR 文件

运行接收文件上传的服务器端组件。日志输出会显示出来。服务应该会在几秒钟内启动并运行。

在服务器运行后,您需要打开浏览器并访问 http://localhost:8080/ 以查看上传表单。选择一个(较小的)文件并点击 上传。您应该会看到控制器返回的成功页面。如果您选择的文件过大,将会看到一个不太美观的错误页面。

随后,您会在浏览器窗口中看到类似以下内容的一行信息:

“您已成功上传 <您的文件名>!”

测试您的应用程序

在我们的应用程序中有多种方法来测试这一特定功能。以下代码示例(来自src/test/java/com/example/uploadingfiles/FileUploadTests.java)展示了一个使用MockMvc的示例,这样就不需要启动servlet容器:

package com.example.uploadingfiles;

import java.nio.file.Paths;
import java.util.stream.Stream;

import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.example.uploadingfiles.storage.StorageFileNotFoundException;
import com.example.uploadingfiles.storage.StorageService;

@AutoConfigureMockMvc
@SpringBootTest
public class FileUploadTests {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private StorageService storageService;

    @Test
    public void shouldListAllFiles() throws Exception {
        given(this.storageService.loadAll())
                .willReturn(Stream.of(Paths.get("first.txt"), Paths.get("second.txt")));

        this.mvc.perform(get("/")).andExpect(status().isOk())
                .andExpect(model().attribute("files",
                        Matchers.contains("http://localhost/files/first.txt",
                                "http://localhost/files/second.txt")));
    }

    @Test
    public void shouldSaveUploadedFile() throws Exception {
        MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt",
                "text/plain", "Spring Framework".getBytes());
        this.mvc.perform(multipart("/").file(multipartFile))
                .andExpect(status().isFound())
                .andExpect(header().string("Location", "/"));

        then(this.storageService).should().store(multipartFile);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void should404WhenMissingFile() throws Exception {
        given(this.storageService.loadAsResource("test.txt"))
                .willThrow(StorageFileNotFoundException.class);

        this.mvc.perform(get("/files/test.txt")).andExpect(status().isNotFound());
    }

}

在那些测试中,您使用各种模拟来设置与控制器和 StorageService 的交互,同时也通过使用 MockMultipartFile 来与 Servlet 容器本身进行交互。

关于集成测试的示例,请参阅 FileUploadIntegrationTests 类(位于 src/test/java/com/example/uploadingfiles 中)。

总结

恭喜!您刚刚编写了一个使用 Spring 处理文件上传的 Web 应用程序。

另请参阅

以下指南可能也会有所帮助:

本页目录