Springブートファイルのアップロードの例
この記事では、Spring Boot Webアプリケーションでファイルをアップロードする方法を説明します。
使用されるツール:
-
春のブート1.4.3.RELEASE
-
Spring 4.3.5.RELEASE
-
タイメレフ
-
Maven
-
埋め込みTomcat 8.5.6
1.プロジェクトの構成
標準的なプロジェクト構造。

プロジェクトの依存関係
春のブートの依存関係は、ファイルアップロードのための余分なライブラリを必要としません。
pom.xml
<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
http://maven.apache.org/maven-v4__0__0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong</groupId>
<artifactId>spring-boot-file-upload</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- hot swapping, disable cache for template, enable live reload -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Package as an executable jar/war -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.ファイルアップロードの例
スプリングブートファイルのアップロード、ゼロ設定。
3.1コントローラでは、アップロードされたファイルを `MultipartFile`にマップします。
UploadController.java
package com.mkyong.controller;
import org.springframework.stereotype.Controller;
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 org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class UploadController {
//Save the uploaded file to this folder
private static String UPLOADED__FOLDER = "F://temp//";
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("/upload")////new annotation since 4.3
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
//Get the file and save it somewhere
byte[]bytes = file.getBytes();
Path path = Paths.get(UPLOADED__FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
}
3.2 thymeleafでは、いくつかの通常のHTMLファイルタグ。
upload.jsp
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"/><br/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
3.3アップロードステータスの別のページ
uploadStatus.jsp
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot - Upload Status</h1>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
4.最大アップロードサイズを超えました
最大アップロードサイズを処理するには例外を超え、
@ ControllerAdvice`を宣言し、
MultipartException`をキャッチします。
GlobalExceptionHandler.java
package com.mkyong.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@ControllerAdvice
public class GlobalExceptionHandler {
//https://jira.spring.io/browse/SPR-14651
//Spring 4.3.5 supports RedirectAttributes
@ExceptionHandler(MultipartException.class)
public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
return "redirect:/uploadStatus";
}
/** Spring < 4.3.5
@ExceptionHandler(MultipartException.class)
public String handleError2(MultipartException e) {
return "redirect:/errorPage";
}** /
}
5. Tomcat接続のリセット
Tomcatにデプロイした場合、このリンクを避けるように `maxSwallowSize`を設定してください://spring/spring-file-upload-and-connection-reset-issue/[Tomcat connection reset issue]埋め込みTomcatの場合、次のような `TomcatEmbeddedServletContainerFactory`を宣言します:
SpringBootWebApplication.java
package com.mkyong;
import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringBootWebApplication {
private int maxUploadSizeInMb = 10 ** 1024 ** 1024;//10 MB
public static void main(String[]args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
//Tomcat large file upload connection reset
////spring/spring-file-upload-and-connection-reset-issue/ @Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
}
6.マルチファイルのファイルサイズ
デフォルトでは、Spring Bootの最大ファイルアップロードサイズは1MBです。次のアプリケーションプロパティを使用して値を設定できます。
application.properties
#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties #search multipart spring.http.multipart.max-file-size=10MB spring.http.multipart.max-request-size=10MB
デモ
デフォルトの埋め込みTomcat `mvn spring-boot:run`でSpringブートを開始します。
ターミナル
$ mvn spring-boot:run . ________ __ ____ __ __ /\\/______'__ ____ __ __(__)__ ____ ____ __ \ \ \ \ ( ( )\______ | '__ | '__| | '__ \/__` | \ \ \ \ \\/ ______)| |__)| | | | | || (__| | ) ) ) ) ' |________| .____|__| |__|__| |__\____, |//// =========|__|==============|______/=/__/__/__/ :: Spring Boot :: (v1.4.3.RELEASE) 2017-01-21 07:48:53 INFO com.mkyong.SpringBootWebApplication - Starting SpringBootWebApplication on MKYONG-WIN10 with PID 2384 (E:\spring-boot-file-upload\target\classes started by mkyong in E:\spring-boot-file-upload) 2017-01-21 07:48:53 DEBUG com.mkyong.SpringBootWebApplication - Running with Spring Boot v1.4.3.RELEASE, Spring v4.3.5.RELEASE 2017-01-21 07:48:53 INFO com.mkyong.SpringBootWebApplication - No active profile set, falling back to default profiles: default 2017-01-21 07:48:55 INFO com.mkyong.SpringBootWebApplication - Started SpringBootWebApplication in 2.54 seconds (JVM running for 2.924)
7.1アクセス
http://localhost:8080/

7.2ファイルを選択してアップロードします。

7.3 10MB以上のファイルを選択すると、このページにアクセスします。

8.ソースコードをダウンロードする
ダウンロード:
spring-boot-file-upload-example.zip
(7 KB)
参考文献
ブート共通アプリケーションのプロパティ]。 link://spring-mvc/spring-mvc-file-upload-example/[Spring MVCファイル
アップロードの例]。リンク://spring/spring-exceptionhandler-and-redirectattributes/[Spring
@ExceptionHandlerとRedirectAttributes]。リンク://spring-boot/spring-boot-hello-world-example-thymeleaf/[Spring
ブートHello Worldの例 – Thymeleaf]
リンク://タグ/ファイルアップロード/[ファイルアップロード]リンク://タグ/マルチパート/[マルチパート]
spring boot