Springブートファイルのアップロードの例

Spring Bootファイルのアップロードの例

この記事では、Spring Boot Webアプリケーションでファイルをアップロードする方法を示します。

使用ツール:

  1. Spring Boot 1.4.3.RELEASE

  2. Spring 4.3.5.RELEASE

  3. タイムリーフ

  4. メーベン

  5. 組み込みTomcat 8.5.6

1. プロジェクト構造

標準プロジェクト構造。

spring-boot-file-upload-example-directory

2. プロジェクトの依存関係

Springブート依存関係。ファイルのアップロードに追加のライブラリは不要です。

pom.xml


         4.0.0

    com.example
    spring-boot-file-upload
    jar
    1.0

    
        org.springframework.boot
        spring-boot-starter-parent
        1.4.3.RELEASE
    

    
        1.8
    

    

        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
        
            org.springframework.boot
            spring-boot-devtools
            true
        

    

    
        
            
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

3. ファイルアップロードの例

Springブートファイルのアップロード、設定なし。

3.1 In the Controller, maps the uploaded file to MultipartFile

UploadController.java

package com.example.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 In thymeleaf, just some normal HTML file tags.

upload.jsp





Spring Boot file upload example



3.3 Another page for upload status

uploadStatus.jsp





Spring Boot - Upload Status

4. 最大アップロードサイズを超えました

最大アップロードサイズ超過例外を処理するために、@ControllerAdviceを宣言し、MultipartExceptionをキャッチします

GlobalExceptionHandler.java

package com.example.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にデプロイした場合は、このTomcat connection reset issueを回避するようにmaxSwallowSizeを構成します。 組み込みTomcatの場合、次のようにTomcatEmbeddedServletContainerFactoryを宣言します。

SpringBootWebApplication.java

package com.example;

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
    //http://www.example.com/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

7. DEMO

デフォルトの組み込みTomcatmvn spring-boot:runを使用してSpringBootを起動します。

ターミナル

$ mvn spring-boot:run
 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.3.RELEASE)

2017-01-21 07:48:53 INFO  com.example.SpringBootWebApplication - Starting SpringBootWebApplication on MKYONG-WIN10 with PID 2384 (E:\spring-boot-file-upload\target\classes started by example in E:\spring-boot-file-upload)
2017-01-21 07:48:53 DEBUG com.example.SpringBootWebApplication - Running with Spring Boot v1.4.3.RELEASE, Spring v4.3.5.RELEASE
2017-01-21 07:48:53 INFO  com.example.SpringBootWebApplication - No active profile set, falling back to default profiles: default
2017-01-21 07:48:55 INFO  com.example.SpringBootWebApplication - Started SpringBootWebApplication in 2.54 seconds (JVM running for 2.924)

spring-boot-file-upload-example

7.2 Select a file and upload it.

spring-boot-file-upload-example-2

7.3 Select a file larger than 10mb, you will visit this page.

spring-boot-file-upload-example-3

8. ソースコードをダウンロード

ダウンロード-spring-boot-file-upload-example.zip(7 KB)