Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to pass a single item as multipart using retrofit?

 @Multipart
@POST("/api/add-deal/")
public void addDeal(@Body Deal deal, @Part("image")TypedFile image,Callback<Response> callback);

I want to send only the image as multipart and the rest as is.Is there any possible way ? Even I tried to add TypedFile inside my Deal model but unable to annotate with @part

like image 762
sreejith v s Avatar asked Dec 10 '25 04:12

sreejith v s


1 Answers

Yes, it is possible with Partmap annotation using hash map. For example-

    @Multipart
    @POST("/api/add-deal/")
    Call<Response> addDeal(@PartMap 
    HashMap<String, RequestBody> hashMap);

In hashMap you can add no of url parameters as key and set your values using RequestBody class type. see how to convert String and Image to RequestBody.

    public static RequestBody ImageToRequestBody(File file) { //for image file to request body
           return RequestBody.create(MediaType.parse("image/*"),file);
    }

    public static RequestBody StringToRequestBody(String string){ // for string to request body
           return RequestBody.create(MediaType.parse("text/plain"),string);
    }

add params to hashmap-

    hashMap.put("photo",ImageToRequestBody(imageFile)); //your imageFile to Request body.
    hashMap.put("user_id",StringToRequestBody("113"));
    //calling addDeal method
    apiInterface.addDeal(hashMap);

Hope this helpful.

like image 157
Manpreet Singh Avatar answered Dec 12 '25 18:12

Manpreet Singh