Pandu Abbiyuarsyah
Pandu Abbiyuarsyah

Reputation: 126

How to upload image with Retrofit Android?

I have a function to request upload image with Retrofit like this

void uploadPhoto(File file) {
    RequestBody photo = RequestBody.create(MediaType.parse("application/image"), file);
    RequestBody body = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("photo", file.getName(), photo)
            .build();

    fragment.showProgressDialog(fragment.loading);
    fragment.getApi().uploadPhoto(PrefHelper.getString(PrefKey.TOKEN), body)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Observer<GenericResponse>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    fragment.dismissProgressDialog();
                    Timber.e(e.getMessage());
                }

                @Override
                public void onNext(GenericResponse response) {
                    fragment.dismissProgressDialog();

                    if (response.getCode() == 1) {
                        fragment.showSuccessDialog("Saving success", false);
                        userInfo();
                    }

                }
            });
}

and for the example, I have a button to upload image in my fragment

  @OnClick(R.id.btnChangePicture)
    void onChangePictureClicked() {

}

What code should i put in

OnChangePictureClicked

So i can choose an image from gallery and then I request it to API.

void uploadPhoto(File file)

Thanks

Upvotes: 1

Views: 9204

Answers (3)

MGDiez
MGDiez

Reputation: 111

Transform your image to an array of bytes and then create an Object Dto like the example below and send it to the server through Retrofit.

@Data
public class SetProfileImageRequestDto {
    @SerializedName("Token")
    private String token;

    @SerializedName("Stream")
    private byte[] image;

}

Retrofit Api Service:

    @POST("SetProfileImage/")
    Observable<ResultResponseDto> setProfileImage(@Body SetProfileImageRequestDto profileImageRequestDto);

Hope it works.

Upvotes: 1

Lovekush Vishwakarma
Lovekush Vishwakarma

Reputation: 3169

You can use multipart with retrofit please look this example of image upload using retrofit, its best for you.

its working for me.

//Create Upload Server Client
        ApiService service = RetroClient.getApiService();

        //File creating from selected URL
        File file = new File(imagePath);

        // create RequestBody instance from file
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part body =
                MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile);

        Call<Result> resultCall = service.uploadImage(body);

        resultCall.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {

                progressDialog.dismiss();

                // Response Success or Fail
                if (response.isSuccessful()) {
                    if (response.body().getResult().equals("success"))
                        Snackbar.make(parentView, R.string.string_upload_success, Snackbar.LENGTH_LONG).show();
                    else
                        Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show();

                } else {
                    Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show();
                }

                /**
                 * Update Views
                 */
                imagePath = "";
                textView.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                progressDialog.dismiss();
            }
        });

http://www.pratikbutani.com/2016/06/android-upload-image-file-using-retrofit-2-0/

Upvotes: 0

Sahil Munjal
Sahil Munjal

Reputation: 483

Create a Uri object in Activity or fragment.

private Uri selectedImage;

After that, You will get gallery result in onActivityResult.

     @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
                   selectedImage = data.getData();
                }
            }

Then in your onChangePictureClicked method.

    @OnClick(R.id.btnChangePicture)
        void onChangePictureClicked() {
           if(selectedImage !=null){
             uploadPhoto(new File(selectedImage.getPath()));
           }
        }

Upvotes: 0

Related Questions