index.html代码
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </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代码
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </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"; } }