Android Image Upload with Retrofit 2

Here is how to upload image with Retrofit 2 library on android.
Below is the service source code.

@Multipart
@POST(InatURL.OBSERVATION_PHOTO)
Call<ImageResponse> iNatObservationPhoto(@Part("file\"; filename=\"my_image.jpg\" ") RequestBody image);

And here is how I use it.

File photo = new File(imagePathLocation);
RequestBody photoBody = RequestBody.create(MediaType.parse("image/jpg"), photo);

// Synchronous.
Response<ImageResponse> response = service.iNatObservationPhoto(photoBody).execute();

// Asynchronous.
service.iNatObservationPhoto(photoBody).enqueue(new Callback<ImageResponse>() {
    @Override
    public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {
    }

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

Reference: https://github.com/square/retrofit/issues/1063#issuecomment-144246407

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s