1. 程式人生 > >SpringBoot 學習系列(八)

SpringBoot 學習系列(八)

1、maven配置(web專案 和 thymeleaf模板引擎)

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

 2、寫上傳前端頁面和上傳結果展示頁面

      上傳頁面 index.html 關鍵程式碼如下:

<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>

      結果展示頁面 uploadStatus.html頁面如下:

<!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>

3、編寫Controller程式碼如下

 @PostMapping("/upload")
    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( file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:uploadStatus";
    }

    @RequestMapping("/uploadStatus")
    public String us(Model model){
        return "uploadStatus";
    }

  注意別忘寫 uploadStatus 這個方法,沒有這個方法,檢視將無法顯示,return的時候別帶最前面的路徑符號 /

4、測試

      選擇完檔案,點選上傳

     跳轉到上傳狀態頁面