LoginSignup
21
27

More than 5 years have passed since last update.

Springbootでファイルをアップロードする

Last updated at Posted at 2018-09-16

Springbootでファイルアップロードします。

Springboot+JQueryを使ってDRAG&DROPでファイルをアップロードする。では、Drag Dropでのアップロードでしたが、今回は、input type="file" でアップロードし、ファイルをサーバのフォルダに保存するまでを試します。

1.html

index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>top page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2>ファイルアップロード</h2>
    <form method="post" enctype="multipart/form-data" th:action="@{/upload}" th:object="${form}" >
        <input th:field="*{file}" type="file" multiple/>
        <input type="submit" value="送信する"/>
    </form>
</body>
</html>

複数選択可能にします。

2.ファイルアップロード

UploadForm.java
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import lombok.Data;
@Data
public class UploadForm {
  private List<MultipartFile> file;
}

Listで複数のファイルに対応します

3.Controller

FileUploadController.java

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

    private String getExtension(String filename) {
      int dot = filename.lastIndexOf(".");
      if (dot > 0) {
        return filename.substring(dot).toLowerCase();
      }
      return "";
    }

    private String getUploadFileName(String fileName) {

        return fileName + "_" +
                DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
                    .format(LocalDateTime.now())
                + getExtension(fileName);
    }

    private void createDirectory() {
        Path path = Paths.get("C:/upload/files");
        if (!Files.exists(path)) {
          try {
            Files.createDirectory(path);
          } catch (Exception e) {
            //エラー処理は省略
          }
        }
    }

    private void savefile(MultipartFile file) {
      String filename = getUploadFileName(file.getOriginalFilename());
      Path uploadfile = Paths.get("C:/upload/files/" + filename);
      try (OutputStream os = Files.newOutputStream(uploadfile, StandardOpenOption.CREATE)) {
        byte[] bytes = file.getBytes();
        os.write(bytes);
      } catch (IOException e) {
        //エラー処理は省略
      }
    }

    private void savefiles(List<MultipartFile> multipartFiles) {
        createDirectory();
        for (MultipartFile file : multipartFiles) {
            savefile(file);
        }
    }

    @RequestMapping(path = "/", method = RequestMethod.GET)
    String uploadview(Model model) {
      model.addAttribute("form", new UploadForm());
      return "index";
    }

    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    String upload(Model model, UploadForm form) {
      if (form.getFile()==null || form.getFile().isEmpty()) {
        //エラー処理は省略
        return "index";
      }
      savefiles(form.getFile());
      return "redirect:/";
    }
}

4.結果

image.png

アップロードされました。

21
27
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
27