Nivedh
Nivedh

Reputation: 961

How to upload multipart image data in JSON with retrofit 2 in android?

How can i upload image file along with my json.

My request JSON looks in the below format.

{
    "Request": {
        "first_name": "Josmy",
        "last_name": "J",
        "profile_image_attributes": {
            "image":"file"
        }
    }
}

In my gson class i am inputting values some what like this

public class Request implements Serializable {
    @SerializedName("first_name")
    private String firstName;
    @SerializedName("last_name")
    private String lastName;
    @SerializedName("profile_image_attributes")
    private MultipartBody.Part profileImageAttributes;
}

@Headers("Content-Type:application/json")
@POST(PSDApiconstants.REGISTRATION)
Observable<PSDSignUpResponseBean> registration(@Body PSDRegistrationRequestBean requestBean);

is there any way without changing the request to

  {
      "imag": "File",
      "first_name": "Josmy",
      "last_name": "J",
    }

EDIT

Currently I think retrofit 2.0.1 dosen't support image upload in this pattern. so i use Asynchttp to solve this problem. But may be retrofit 2 will include this in their latest release by the end of july

Upvotes: 1

Views: 13335

Answers (2)

Raghav Sharma
Raghav Sharma

Reputation: 43

You can send Multipart File along with JSON as string in RequestBody. Here's an example of sending multiple images with JSON. This is how your service method should look like

@Multipart
@POST("/addCountry")
fun addCountry(@Part images: List<MultipartBody.Part>,@Part("country") country:RequestBody):Call<String>

And while calling the retrofit api

val image= mutableListOf<MultipartBody.Part>()
        images.forEach {
            image.add(MultipartBody.Part.
                        createFormData(
                            "images",
                            it.name,
                            RequestBody.create(MediaType.parse("image/*"),it)
                        )
                    )
        }
val reqBody=RequestBody.create(MediaType.parse("text/plain"),json)
val call = APIClient.CountryAPI.addCountry(image,reqBody)

The 'json' variable is string which stores the JSON of your object. You can use Gson to convert your object into JSON.

Upvotes: 0

ikhsanudinhakim
ikhsanudinhakim

Reputation: 1634

In retrofit 2.0 you can upload image using MultipartBody.Part.

Declare your service

@Multipart
@POST("/api/imageupload")
Observable<Response> uploadImage(@Part MultipartBody.Part imageFile);

Create your retrofit client object and call your api.

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(YOUR_API_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

//prepare image file
File file = new File(imagePath);
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part imageFileBody = MultipartBody.Part.createFormData("image", file.getName(), requestBody);

YourAPI service = retrofit.create(YourAPI.class);
Call<Response> call = service.uploadImage(imageFileBody);
call.enqueue(new Callback<Response>() {
    @Override
    public void onResponse(Call<Response> call, Response<Response> response) {
        //handle success
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
        //handle error
    }
}

Upvotes: 1

Related Questions