SpringBoot
[Springboot] api 컨트롤러에서 json형식의 데이터와 MultipartFile 동시에 받기
윤윤쿤
2024. 5. 13. 17:20
한개의 컨트롤러에서 json 데이터와 MultipartFile 을 한번에 받으려 할때
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class User {
private String id;
private String pw;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date birth;
private List<String> myList;
private String imgPath;
}
@PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> createUser(@RequestParam("user") User testDataJson,
@RequestPart("file") MultipartFile file) throws Exception{
}
컨트롤러에서 User형식 그대로 받으려하면 자꾸 오류가 발생했었다.
파일 데이터를 받으려면 @RequestPart로 받아야하는데 @RequestPart는 @RequestParam과 같이 사용할 수 없어 오류가 발생했다.
@ModelAttribute를 사용해도 되지만 파일을 새로 만들긴 싫어서 패스,,,
그래서 방법을 찾다가 발견한것이 String형식으로 받은뒤 objectMapper를 이용하여 매핑해주는 방법이다.
controller는 다음과 같다.
Controller.java
@PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> createUser(@RequestParam("user") String testDataJson,
@RequestPart("file") MultipartFile file) throws Exception{
String response = testService.createUser(testDataJson,file);
return ResponseEntity.ok(response);
}
createUser에서 매핑 후 데이터를 저장하면 된다.
public String createUser(String userJson, MultipartFile file) throws Exception{
//userJson Test 형식으로 매핑
ObjectMapper objectMapper = new ObjectMapper().registerModule(new SimpleModule());
Test user = objectMapper.readValue(userJson, Test.class);
}
@ModelAttribute를 사용하는 경우
엔티티 클래스에 MultiparFile 형식의 엔티티를 추가해준다.
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class User {
private String id;
private String pw;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date birth;
private List<String> myList;
private MultipartFile imgPath;
}
Controller
@PostMapping(value = "/",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> postDetail(@ModelAttribute User user)
throws ExecutionException, InterruptedException {
String response = testService.createUser(testDataJson,file);
return ResponseEntity.ok(response);
}