Spring boot+thymeleaf文件上传实现

index.html代码

html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">上传button>
form>
body>
html>

uploadStatus.html代码

html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<div th:if="${ message }">
    <h2 th:text="${ message }"/>
div>
body>
html>

controller层代码

@Controller
public class FileUploadController {

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model){
        if (file.isEmpty()){
            model.addAttribute("message", "The file is empty!");
            return "/uploadStatus";
        }
        try{
            byte[] bytes = file.getBytes();
            Path path = Paths.get("E:\\fileUpload/" + file.getOriginalFilename());
            Files.write(path, bytes);
            model.addAttribute("message", "succes");

        }catch (Exception e){
            e.printStackTrace();
        }
        return "/uploadStatus";
    }
}

你可能感兴趣的:(Spring boot+thymeleaf文件上传实现)