본문 바로가기

안드로이드 스튜디오

[ 안드로이드 ] Retrofit으로 파일 업로드 하기

Multipart 란?

HTTP를 통해 File을 Server로 전송하기 위해 사용되는 Content-type이다. HTTP 프로토콜은 크게 Header와 Body로 구분이 되고, 데이터는 Body에 들어가서 전송이 되는데, Body에 들어가는 데이터 타입을 명시해주는게 Content-type이다.

 

API 코드

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

 

Activity 코드

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(getApplicationContext(), " 업로드가 완료되었습니다.", Toast.LENGTH_SHORT).show();
        finish();
    }

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