본문 바로가기
  • 콩's 코딩노트
Android

Android Studio - Retrofit 에서 Multi form으로 데이터를 보내는 방법

by Cong_S 2022. 7. 26.

1. Api 인터페이스 만들기

public interface PostingApi {

    @Multipart
    @POST("/posting")
    Call<PostRes> addPosting(@Header("Authorization") String token,
                             @Part MultipartBody.Part photo,
                             @Part ("content")RequestBody content);

 

2. 파일을 보낼 때 액티비티에서의 코드

// 멀티파트로 파일을 보내는 경우, 파일 파라미터 만드는 방법
RequestBody fileBody = RequestBody.create(photoFile, MediaType.parse("image/*"));
MultipartBody.Part photo = MultipartBody.Part.createFormData("photo",
        photoFile.getName(), fileBody);

 

2-1. 텍스트를 보낼 때 액티비티에서의 코드

// 멀티파트로 텍스트를 보내는 경우, 파라미터 만드는 방법
RequestBody contentBody = RequestBody.create(content, MediaType.parse("text/plain"));

 

 

아래 예시는 버튼을 눌렀을 때 에디트 텍스트와 입력된 이미지를 네트워크를 통해 S3와 데이터베이스에 업로드하는 코드이다.

더보기
btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(photoFile == null){
                    Toast.makeText(AddActivity.this, "사진을 선택하세요.", Toast.LENGTH_SHORT).show();
                    return;
                }

                String content = editContent.getText().toString().trim();

                if(content.isEmpty()){
                    Toast.makeText(AddActivity.this, "내용을 입력하세요.", Toast.LENGTH_SHORT).show();
                    return;
                }

                Retrofit retrofit = NetworkClient.getRetrofitClient(AddActivity.this);
                PostingApi api = retrofit.create(PostingApi.class);

                // 멀티파트로 파일을 보내는 경우, 파일 파라미터 만드는 방법
                RequestBody fileBody = RequestBody.create(photoFile, MediaType.parse("image/*"));
                MultipartBody.Part photo = MultipartBody.Part.createFormData("photo",
                        photoFile.getName(), fileBody);
                // 멀티파트로 텍스트를 보내는 경우, 파라미터 만드는 방법
                RequestBody contentBody = RequestBody.create(content, MediaType.parse("text/plain"));

                // 헤더에 들어갈 억세스토큰 가져온다.
                SharedPreferences sp = getApplication().getSharedPreferences(Config.PREFERENCES_NAME, MODE_PRIVATE);
                String accessToken = sp.getString("accessToken", "");

                Call<PostRes> call = api.addPosting("Bearer "+accessToken,
                        photo,
                        contentBody);

                showProgress("포스팅 업로드 중...");

                call.enqueue(new Callback<PostRes>() {
                    @Override
                    public void onResponse(Call<PostRes> call, Response<PostRes> response) {
                        dismissProgress();

                        Toast.makeText(AddActivity.this, "업로드가 완료되었습니다.", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onFailure(Call<PostRes> call, Throwable t) {
                        dismissProgress();
                    }
                });

            }
        });

댓글