Loading...
Spring Framework Reference Documentation 7.0.2의 Multipart의 한국어 번역본입니다.
아래의 경우에 피드백에서 신고해주신다면 반영하겠습니다.
감사합니다 :)
MultipartResolver가 enabled된 후에는 multipart/form-data를 가진 POST 요청의 콘텐츠가 파싱되어 일반적인 요청 파라미터처럼 접근할 수 있습니다. 다음 예제는 하나의 일반 폼 필드와 하나의 업로드된 파일에 접근하는 예제입니다:
1@Controller 2public class FileUploadController { 3 4 @PostMapping("/form") 5 public String handleFormUpload(@RequestParam("name") String name, 6 @RequestParam("file") MultipartFile file) { 7 8 if (!file.isEmpty()) { 9 byte[] bytes = file.getBytes(); 10 // store the bytes somewhere 11 return "redirect:uploadSuccess"; 12 } 13 return "redirect:uploadFailure"; 14 } 15}
1@Controller 2class FileUploadController { 3 4 @PostMapping("/form") 5 fun handleFormUpload( 6 @RequestParam("name") name: String, 7 @RequestParam("file") file: MultipartFile 8 ): String { 9 10 if (!file.isEmpty) { 11 val bytes = file.bytes 12 // store the bytes somewhere 13 return "redirect:uploadSuccess" 14 } 15 return "redirect:uploadFailure" 16 } 17}
argument 타입을 List<MultipartFile>로 선언하면 동일한 파라미터 이름에 대해 여러 개의 파일을 resolving할 수 있습니다.
@RequestParam 어노테이션이 어노테이션에서 파라미터 이름이 지정되지 않은 Map<String, MultipartFile> 또는 MultiValueMap<String, MultipartFile>로 선언된 경우, 맵은 각 주어진 파라미터 이름에 대한 multipart 파일로 채워집니다.
| 타입 | 설명 |
|---|---|
jakarta.servlet.http.Part | Servlet multipart 파싱을 사용하는 경우, 메서드 argument 또는 컬렉션 값 타입으로 Spring의 MultipartFile 대신 jakarta.servlet.http.Part를 선언할 수도 있습니다. |
multipart 콘텐츠는 command 객체의 데이터 바인딩의 일부로도 사용할 수 있습니다. 예를 들어, 앞선 예제의 폼 필드와 파일은 다음 예제에서 보이는 것처럼 폼 객체의 필드가 될 수 있습니다:
1class MyForm { 2 3 private String name; 4 5 private MultipartFile file; 6 7 // ... 8} 9 10@Controller 11public class FileUploadController { 12 13 @PostMapping("/form") 14 public String handleFormUpload(MyForm form, BindingResult errors) { 15 if (!form.getFile().isEmpty()) { 16 byte[] bytes = form.getFile().getBytes(); 17 // store the bytes somewhere 18 return "redirect:uploadSuccess"; 19 } 20 return "redirect:uploadFailure"; 21 } 22}
1class MyForm(val name: String, val file: MultipartFile, ...) 2 3@Controller 4class FileUploadController { 5 6 @PostMapping("/form") 7 fun handleFormUpload(form: MyForm, errors: BindingResult): String { 8 if (!form.file.isEmpty) { 9 val bytes = form.file.bytes 10 // store the bytes somewhere 11 return "redirect:uploadSuccess" 12 } 13 return "redirect:uploadFailure" 14 } 15}
multipart 요청는 RESTful 서비스 시나리오에서 non-browser 클라이언트로부터도 전송될 수 있습니다. 다음 예제는 JSON과 함께 파일을 보여줍니다:
1POST /someUrl 2Content-Type: multipart/mixed 3 4--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp 5Content-Disposition: form-data; name="meta-data" 6Content-Type: application/json; charset=UTF-8 7Content-Transfer-Encoding: 8bit 8 9{ 10 "name": "value" 11} 12--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp 13Content-Disposition: form-data; name="file-data"; filename="file.properties" 14Content-Type: text/xml 15Content-Transfer-Encoding: 8bit 16... File Data ...
"meta-data" part에 @RequestParam을 사용하여 String으로 접근할 수 있지만, 아마도 JSON에서 역직렬화되기를 원할 것입니다 (@RequestBody와 유사). multipart를 HttpMessageConverter를 사용해 변환한 후 접근하려면 @RequestPart 어노테이션을 사용하십시오:
1@PostMapping("/") 2public String handle(@RequestPart("meta-data") MetaData metadata, 3 @RequestPart("file-data") MultipartFile file) { 4 // ... 5}
1@PostMapping("/") 2fun handle( 3 @RequestPart("meta-data") metadata: MetaData, 4 @RequestPart("file-data") file: MultipartFile 5): String { 6 // ... 7}
@RequestPart는 jakarta.validation.Valid와 함께 사용하거나 Spring의 @Validated 어노테이션을 사용할 수 있으며, 둘 다 Standard Bean Validation이 적용되도록 합니다. 기본적으로 validation error는 MethodArgumentNotValidException을 발생시키며, 이는 400 (BAD_REQUEST) 응답으로 변환됩니다. 또는 다음 예제에서 보이는 것처럼 Errors 또는 BindingResult argument를 통해 컨트롤러 내에서 로컬로 validation error를 처리할 수도 있습니다:
1@PostMapping("/") 2public String handle(@Valid @RequestPart("meta-data") MetaData metadata, Errors errors) { 3 // ... 4}
1@PostMapping("/") 2fun handle(@Valid @RequestPart("meta-data") metadata, errors: Errors): String { 3 // ... 4}
다른 파라미터에 @Constraint 어노테이션이 있어서 메서드 validation이 적용되는 경우, 대신 HandlerMethodValidationException이 발생합니다. 더 자세한 내용은 Validation 섹션을 참조하십시오.
Flash Attributes
@RequestBody