Spring Boot에서 RequestBody, MultipartFile 저장하기

Android

  • AccountEditRequest data class
data class AccountEditRequest(
    var id : RequestBody?,
    var userId : RequestBody?,
    var name : RequestBody?,
    var message : RequestBody?,
    var profileImage : MultipartBody.Part?,
    var backImage : MultipartBody.Part?
){
    override fun toString(): String {
        return "AccountEditRequest(user_id=$userId, user_img=$profileImage, back_img=$backImage)"
    }
}
  • AccountInfoActivity
                viewModel.edit(
                    AccountEditRequest(
                    createPartFromString(it),
                    createPartFromString(userId),
                    createPartFromString(userName),
                    createPartFromString(userMsg),
                    prepareFilePart("profileImage",profileImage),
                    prepareFilePart("backImage",backImage))
                )
  • AccountAPI
    @POST("/api/account/edit")
    @Multipart
    //@Path 와 @Part 동시에 사용 못하네
    fun updateAccount(
        @Part("id") id : RequestBody?,
        @Part("userId") userId : RequestBody?,
        @Part("name") name : RequestBody?,
        @Part("message") message : RequestBody?,
        @Part images : Array<MultipartBody.Part?>?
    ) : Single<BaseResponse>

Spring Boot Application

// https://blogs.perficient.com/2020/07/27/requestbody-and-multipart-on-spring-boot/
    @PostMapping(
            value = "/api/account/edit" ,
            consumes = {
                    MediaType.MULTIPART_FORM_DATA_VALUE,
                    MediaType.APPLICATION_JSON_VALUE
            }
            )

    public BaseResponseDto profileUpdate(
            @RequestPart(value = "id", required = false) String id,
            @RequestPart(value = "userId", required = false) String userId,
            @RequestPart(value = "name", required = false) String name,
            @RequestPart(value = "message",required = false) String message,
            @RequestPart(value = "profileImage",required = false) MultipartFile profileImage,
            @RequestPart(value = "backImage", required = false) MultipartFile backImage
    ) {
        return userService.profileUpdate(UserProfileUpdateRequestDto.builder()
                .id(id)
                .userId(userId)
                .name(name)
                .message(message)
                .profileImage(profileImage)
                .backImage(backImage)
                .build());
    }
  • UserProfileUpdateRequestDto
@Getter
@NoArgsConstructor
public class UserProfileUpdateRequestDto {
    private String id;
    private String userId;
    private String name;
    private String message;
    private MultipartFile profileImage;
    private MultipartFile backImage;

    @Builder
    public UserProfileUpdateRequestDto(String id,
                                       String userId,
                                       String name,
                                       String message,
                                       MultipartFile profileImage,
                                       MultipartFile backImage) {
        this.id = id;
        this.userId = userId;
        this.name = name;
        this.message = message;
        this.profileImage = profileImage;
        this.backImage = backImage;
    }

    public User toEntity() {
        return User.builder()
                .userId(userId)
                .name(name)
                .stateMessage(message)
//                .profilePicture(profileImage)
//                .backgroundPicture(backImage)
                .build();
    }
}
  • @RequestPart(value = "id", required = false)
    • required = false해줘야 null 값이 들어와도 코드가 진행된다.
  • public static final String MULTIPART_FORM_DATA_VALUE = "multipart/form-data";

File Access Through URL

@RequiredArgsConstructor
@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final LoginUserArgumentResolver loginUserArgumentResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        // HandleMethodArgumentResolver는 항상 WebMvcConfigurer의 addArgumentResolvers()를 통해 추가해야한다.
        resolvers.add(loginUserArgumentResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String path = "uploads";
        registry
                .addResourceHandler(path + "/**") // url 접근 경로
                .addResourceLocations("file:" + path + "/"); // 디렉토리 경로 (반드시 file: 을 붙여주어야 한다.)
    }
}
  • http://{Spring Boot IP 주소}:{포트 번호}/{폴더 이름}/{파일 이름}로 파일에 접근할 수 있다.

좋은 웹페이지 즐겨찾기