[Spring官方教程] - SpringBoot文件上传

本指南将引导你完成创建一个可以接收HTTPmulti-part file文件上传的服务器应用程序的过程。

你将建造什么

你将创建一个接受文件上传的Spring Boot网络应用程序。你还将建立一个简单的HTML界面来上传一个测试文件。

你需要什么

从Spring Initializr开始

如果你使用Maven,请访问Spring Initializr来生成一个带有所需依赖项(Spring Web和Thymeleaf)的新项目。

下面的列表显示了选择Maven时创建的pom.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>uploading-files-initial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>uploading-files-initial</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

如果你使用Gradle,请访问Spring Initializr的新项目。

下面的列表显示了当你选择Gradle时创建的build.gradle文件。

plugins {
	id 'org.springframework.boot' version '2.5.2'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation('org.springframework.boot:spring-boot-starter-test')\
}

test {
	useJUnitPlatform()
}

手动初始化(可选)

如果你想手动初始化项目,而不是使用前面显示的链接,请按照下面的步骤进行。

  1. 导航到https://start.spring.io。这个服务拉入你的应用程序所需的所有依赖项,并为你做大部分的设置。
  2. 2.选择Gradle或Maven以及你想使用的语言。本指南假设你选择了Java。
  3. 点击Dependencies,选择Spring WebThymeleaf
  4. 单击Generate
  5. 下载生成的ZIP文件,这是一个用你的选择配置的Web应用程序的档案。

如果你的IDE有Spring Initializr集成,你可以从你的IDE完成这个过程。

创建一个Application 类

要启动一个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将创建一个MultipartConfigElementbean,并使自己为文件上传做好准备。

创建一个 File Upload Controller

最初的应用程序已经包含了一些处理在磁盘上存储和加载上传文件的类。它们都位于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);
		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();

}

创建一个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在那里写了一个flash-scoped message
  • 一个让用户上传文件的表单。
  • 一个由后端提供的文件列表。

调整文件上传限制

在配置文件上传时,对文件的大小设置限制往往是有用的。想象一下,要处理一个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。

运行 Application

你想要一个上传文件的目标文件夹,所以你需要增强Spring Initializr创建的基本的UploadingFilesApplication类,并添加一个BootCommandLineRunner来在启动时删除和重新创建该文件夹。下面的列表(来自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开始根据classpath设置、其他Bean和各种属性设置来添加Bean。例如,如果spring-webmvc在classpath上,这个注解将应用程序标记为Web应用程序,并激活关键行为,如设置DispatcherServlet
  • @ComponentScan : 告诉Spring在com/example包中寻找其他组件、配置和服务,让它找到控制器。

main()方法使用Spring Boot的SpringApplication.run()方法来启动一个应用程序。你是否注意到,没有一行XML?也没有web.xml文件。这个网络应用是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.fileUpload;
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处理文件上传的网络应用。你刚刚写了一个使用Spring来处理文件上传的Web应用程序。

另见

下面的指南可能也有帮助。

想写一个新的指南或对现有的指南做出贡献?请查看我们的贡献指南


原文:https://spring.io/guides/gs/uploading-files/