1+ package com .didispace .chapter44 ;
2+
3+ import lombok .extern .slf4j .Slf4j ;
4+ import org .springframework .beans .factory .annotation .Value ;
5+ import org .springframework .stereotype .Controller ;
6+ import org .springframework .web .bind .annotation .GetMapping ;
7+ import org .springframework .web .bind .annotation .PostMapping ;
8+ import org .springframework .web .bind .annotation .RequestPart ;
9+ import org .springframework .web .bind .annotation .ResponseBody ;
10+ import org .springframework .web .multipart .MultipartFile ;
11+
12+ import java .io .File ;
13+ import java .io .IOException ;
14+
15+ @ Controller
16+ @ Slf4j
17+ public class UploadController {
18+
19+ @ Value ("${file.upload.path}" )
20+ private String path ;
21+
22+ @ GetMapping ("/" )
23+ public String uploadPage () {
24+ return "upload" ;
25+ }
26+
27+ @ PostMapping ("/upload" )
28+ @ ResponseBody
29+ public String create (@ RequestPart MultipartFile [] files ) {
30+ StringBuffer message = new StringBuffer ();
31+
32+ for (MultipartFile file : files ) {
33+ String fileName = file .getOriginalFilename ();
34+ String filePath = path + fileName ;
35+
36+ File dest = new File (filePath );
37+ try {
38+ file .transferTo (dest );
39+ message .append ("Upload file success : " + dest .getAbsolutePath ()).append ("<br>" );
40+ } catch (IOException e ) {
41+ log .error (e .getMessage (), e );
42+ message .append ("Upload file failed : " + e .getMessage ()).append ("<br>" );
43+ }
44+ }
45+ return message .toString ();
46+ }
47+
48+ }
0 commit comments