@@ -24,7 +24,7 @@ public String index() {
24
24
25
25
@ PostMapping ("/upload" ) // //new annotation since 4.3
26
26
public String singleFileUpload (@ RequestParam ("file" ) MultipartFile file ,
27
- RedirectAttributes redirectAttributes ) {
27
+ RedirectAttributes redirectAttributes ) {
28
28
if (file .isEmpty ()) {
29
29
redirectAttributes .addFlashAttribute ("message" , "Please select a file to upload" );
30
30
return "redirect:uploadStatus" ;
@@ -33,16 +33,20 @@ public String singleFileUpload(@RequestParam("file") MultipartFile file,
33
33
try {
34
34
// Get the file and save it somewhere
35
35
byte [] bytes = file .getBytes ();
36
+ Path dir = Paths .get (UPLOADED_FOLDER );
36
37
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
+ }
37
42
Files .write (path , bytes );
38
-
39
43
redirectAttributes .addFlashAttribute ("message" ,
40
- "You successfully uploaded '" + file .getOriginalFilename () + "'" );
44
+ "You successfully uploaded '" + file .getOriginalFilename () + "'" );
41
45
42
46
} catch (IOException e ) {
47
+ redirectAttributes .addFlashAttribute ("message" , "Server throw IOException" );
43
48
e .printStackTrace ();
44
49
}
45
-
46
50
return "redirect:/uploadStatus" ;
47
51
}
48
52
0 commit comments