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";
    }
}

 

posted @ 2022-01-13 19:41  IT6889  阅读(55)  评论(0编辑  收藏  举报