【SpringBoot】上傳文件 DEMO——MultipartFile

如果餓了就吃,困了就睡,渴了就喝,人生就太無趣了
源碼地址:https://github.com/keer123456789/springbootstudy/tree/master/multipartfiledemo


1. 依賴設置

		<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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
		</dependency>

使用前端模板引擎thymeleaf來展示文件上傳狀態。

2. 前端頁面

2.1 上傳頁面 upload.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
</head>
<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>

如圖1:
在這裏插入圖片描述

2.2 文件上傳狀態頁面 uploadStauts.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload status</h1>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>

如圖2:
在這裏插入圖片描述

3.上傳邏輯

  1. 訪問http://127.0.0.1:8080,跳轉到上傳文件頁面 upload.html
	@GetMapping("/")
    public String index() {
        return "upload";
    }
  1. 在upload.html填寫好信息後,點擊submit按鈕,發送POST請求
	@PostMapping("/upload")
    public String addPeopleInfo(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException {
        logger.info("接收到請求:/upload");

        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "上傳文件爲空,請重新選擇文件");
            logger.info("上傳文件爲空");
            return "redirect:/uploadStauts";
        }

        String strPath = "multipartfiledemo/file/" + file.getOriginalFilename();
        File nfile = new File(strPath);
        File fileParent = nfile.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        nfile.createNewFile();

        Path path = Paths.get(strPath);
        Files.write(path, file.getBytes());
        redirectAttributes.addFlashAttribute("message",
                "成功上傳文件: '" + file.getOriginalFilename() + "'");
        logger.info("上傳文件成功,文件名稱:" + file.getOriginalFilename());
        return "redirect:/uploadStauts";
    }
  1. 將狀態信息傳入/uploadStauts中。該請求返回前端視圖uploadStauts.html
    @GetMapping("/uploadStauts")
    public String uploadStatus() {
        return "uploadStauts";
    }

參考文檔:迷人的微笑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章