From cf3aa5c759bd0a9636aea978e601e7ea8c33e27b Mon Sep 17 00:00:00 2001 From: bliu <1073842723@qq.com> Date: Wed, 9 Sep 2020 16:51:57 +0800 Subject: [PATCH] fix file upload err cause by parent directory not exists --- .../java/com/neo/controller/UploadController.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/spring-boot-file-upload/src/main/java/com/neo/controller/UploadController.java b/spring-boot-file-upload/src/main/java/com/neo/controller/UploadController.java index 13d3ab4..f72b202 100644 --- a/spring-boot-file-upload/src/main/java/com/neo/controller/UploadController.java +++ b/spring-boot-file-upload/src/main/java/com/neo/controller/UploadController.java @@ -24,7 +24,7 @@ public class UploadController { @PostMapping("/upload") // //new annotation since 4.3 public String singleFileUpload(@RequestParam("file") MultipartFile file, - RedirectAttributes redirectAttributes) { + RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "Please select a file to upload"); return "redirect:uploadStatus"; @@ -33,16 +33,20 @@ public class UploadController { try { // Get the file and save it somewhere byte[] bytes = file.getBytes(); + Path dir = Paths.get(UPLOADED_FOLDER); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); + // Create parent dir if not exists + if(!Files.exists(dir)) { + Files.createDirectories(dir); + } Files.write(path, bytes); - redirectAttributes.addFlashAttribute("message", - "You successfully uploaded '" + file.getOriginalFilename() + "'"); + "You successfully uploaded '" + file.getOriginalFilename() + "'"); } catch (IOException e) { + redirectAttributes.addFlashAttribute("message", "Server throw IOException"); e.printStackTrace(); } - return "redirect:/uploadStatus"; } -- GitLab