Skip to content

Commit cf3aa5c

Browse files
committed
fix file upload err cause by parent directory not exists
1 parent 3f7e091 commit cf3aa5c

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

spring-boot-file-upload/src/main/java/com/neo/controller/UploadController.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public String index() {
2424

2525
@PostMapping("/upload") // //new annotation since 4.3
2626
public String singleFileUpload(@RequestParam("file") MultipartFile file,
27-
RedirectAttributes redirectAttributes) {
27+
RedirectAttributes redirectAttributes) {
2828
if (file.isEmpty()) {
2929
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
3030
return "redirect:uploadStatus";
@@ -33,16 +33,20 @@ public String singleFileUpload(@RequestParam("file") MultipartFile file,
3333
try {
3434
// Get the file and save it somewhere
3535
byte[] bytes = file.getBytes();
36+
Path dir = Paths.get(UPLOADED_FOLDER);
3637
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
38+
// Create parent dir if not exists
39+
if(!Files.exists(dir)) {
40+
Files.createDirectories(dir);
41+
}
3742
Files.write(path, bytes);
38-
3943
redirectAttributes.addFlashAttribute("message",
40-
"You successfully uploaded '" + file.getOriginalFilename() + "'");
44+
"You successfully uploaded '" + file.getOriginalFilename() + "'");
4145

4246
} catch (IOException e) {
47+
redirectAttributes.addFlashAttribute("message", "Server throw IOException");
4348
e.printStackTrace();
4449
}
45-
4650
return "redirect:/uploadStatus";
4751
}
4852

0 commit comments

Comments
 (0)