Java Spring : S3 이미지 저장하기(1)

김선미·2022년 7월 19일
0

프로젝트에서 내가 맡은 기능인 회원 프로필 업데이트 기능 코드를 다시 리뷰하면서 공부하려고 한다. 코드리뷰를 끝내고 나면 이미지 저장 뿐만 아니라 조회, 삭제도 공부하고 구현해보아야겠다.

HTML

파일을 받을 때는 form 태그를 사용하면 전달받은 파일을 javascript에서 formdata 형식으로 만드는 과정을 생략할 수 있는 것 같았지만, 프로젝트 프론트엔드를 건드리고 싶지 않아서 그대로 input 태그를 사용하였다.

User.js

전달받은 input 데이터를 formdata 로 한꺼번에 묶어준다. 닉네임과 상태메세지 두가지만 있었다면 데이터 타입이 string이라 formdata를 사용하지 않아도 된다. file 을 같이 보내기 때문에 반드시 data 형식이 formdata 여야 하고 contenttype, processdata는 false여야 한다.

function update_profile(id) {
    let name = $('#input-user_name').val()
    let file = $('#input-pic')[0].files[0]
    let about = $("#textarea-about").val()

    // 중간 생략: null 값 처리, 닉네임 중복확인 등

    let form_data = new FormData()
    form_data.append("file", file)
    form_data.append("nickname", name)
    form_data.append("statusMessage", about)
    console.log(file, name, about, form_data)
    $.ajax({
        type: "POST",
        url: `/user/update_profile/${id}`,
        data: form_data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {
            if (response["msg"] == "변경 완료!!") {
                alert(response["msg"])
                $("#modal-edit").removeClass("is-active")
                window.location.reload()
            } else {
                alert(response["msg"])
                $("#modal-edit").removeClass("is-active")
            }
        }
    });
}

UpdateController.java

나는 이 컨트롤러 부분과 S3 service 구현이 제일 어려웠다. formdata를 받으면서 설정 해줘야 하는 부분이 많았다.

일단 controller에서는 어떤 로직도 처리하지 않고 오직 service로 데이터를 전달하기만 한다.

@Slf4j
@Controller
@RequiredArgsConstructor
public class UpdateController {

    private final UpdateService updateService;

    @ResponseBody
    @PostMapping(value = "/user/update_profile/{id}", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public UpdateUserResponseDto UpdateProfile(@PathVariable long id, @Validated @ModelAttribute UpdateUserRequestDto updateUserRequestDto, BindingResult result)
            throws IOException {

        UpdateUserResponseDto updateUserResponseDto = updateService.updateProfile(id, updateUserRequestDto);

        return updateUserResponseDto;
    }

!!이어서 작성 예정!!

profile
백엔드 개발 공부

0개의 댓글