1. 程式人生 > 其它 >springboot系列16:檔案上傳

springboot系列16:檔案上傳

檔案上傳用到的場景也比較多,如頭像的修改、相簿應用、附件的管理等等,今天就來學習下在springboot框架下應用檔案上傳技術。

1、pom 配置

    <dependencies>
        <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>
    </dependencies>

2、application.properties配置上傳檔案的大小

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

3、上傳頁面

<!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="上傳" />
</form>
</body>
</html>

4、上傳結果頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>SpringBoot - 檔案上傳結果</h1>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>

5、上傳檔案controller

@Controller
public class UploadController {

    private static String UPLOADED_FOLDER = "E://temp//";

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "請選擇一個檔案上傳");
            return "redirect:uploadStatus";
        }

        try {
            byte[] bytes = file.getBytes();
            File pathFile = new File(UPLOADED_FOLDER);
            if (!pathFile.exists()){
                pathFile.mkdirs();
            }
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message",
                    "檔案上傳成功:'" + file.getOriginalFilename() + "'");

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

        return "redirect:/result";
    }

    @GetMapping("/result")
    public String result() {
        return "result";
    }
}