글을 작성한다고 할때, 제목, 내용을 작성할 수 있다면 다음과 같이 Controller와 dto클래스를 작성할 수 있을 것이다.
@PostMapping("/post")
public ResponseDto<Long> savePost(@Valid @RequestBody PostRequestDto postRequestDto, @AuthenticationPrincipal UserDetailsImpl userDetails) {
return postService.savePost(postRequestDto, userDetails.getMember());
}
@Getter
public class PostRequestDto {
private String title;
private String content;
}
PostMan으로 요청한다면 이렇게 보내면 될 것이다.
프로필 이미지만 변경한다고 했을 때, 다음과 같이 작성할 수 있을 것이다.
@PostMapping(value = "/profile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseDto<String> updateProfile(@RequestParam(value = "image") MultipartFile image, @AuthenticationPrincipal UserDetailsImpl userDetails) {
return memberService.updateProfile(image, userDetails.getMember());
}
그러면 포스트맨으로 요청을 할 때 다음과 같이 보내면 될 것이다.
그렇다면 제목, 내용을 json으로 사진은 MultipartFile로 받고 싶다면 어떻게 해야할까?
@RequestPart 애노테이션을 사용하면 된다.
@RequestPart 애노테이션은 MultipartFile과 dto를 같이 받아야 할 때 사용할 수 있다.
@PutMapping(value = "/{id}/info", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseDto<?> updatePostIndo(@PathVariable Long id,
@Valid @RequestPart(value = "postInfo") PostInfoRequestDto postInfoRequestDto,
@RequestPart(value="thumbnail", required = false) MultipartFile multipartFile) {
return postService.updatePostInfo(id, postInfoRequestDto, multipartFile);
}
PostMan에서 테스트할 때에는 postInfo의 value값으로 PostInfoRequestDto 클래스에 맞는 Json을 작성해주면 된다.
Content-Type을 application/json으로 지정해주어야 한다.
728x90
'Spring' 카테고리의 다른 글
[Spring] Spring WebFlux 간단한 예제 (0) | 2023.05.25 |
---|---|
[Spring] @RequestParam으로 Enum 타입 매개변수 받기 (0) | 2023.05.15 |
[Spring] AWS S3 서비스를 사용하여 이미지 업로드 (0) | 2023.05.09 |
[Spring] EC2 서버 실행 시, Web server failed to start. Port 8080 was aleady in use 해결 (0) | 2023.05.08 |
[Spring] EC2 Connection Time 지정 (0) | 2023.05.08 |