3
 @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

sreejith v s
  • 1,334
  • 10
  • 17

3 Answers3

2

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.

Manpreet Singh
  • 1,048
  • 7
  • 7
0

It seems that you can send your @Body as TypedString.
For example, convert your "@Body Deal deal" into JSON String, and send it as TypedString.

Details: How to send multipart/form-data with Retrofit?

@Multipart
@POST("/api/v1/articles/")
Observable<Response> uploadFile(@Part("author") TypedString authorString,
                                @Part("photo") TypedFile photoFile);
Community
  • 1
  • 1
Stanley Ko
  • 3,383
  • 3
  • 34
  • 60
0

This worked for me: POST Multipart Form Data using Retrofit 2.0 including image

public interface ApiInterface {

    @Multipart
    @POST("/api/Accounts/editaccount")
    Call<User> editUser (@Header("Authorization") String authorization, @Part("file\"; filename=\"pp.png\" ") RequestBody file , @Part("FirstName") RequestBody fname, @Part("Id") RequestBody id);
    }

    File file = new File(imageUri.getPath());
    RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
    RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
    RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
    Call<User> call = client.editUser(AZUtils.getToken(this), fbody, name, id);

    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(retrofit.Response<User> response, Retrofit retrofit) {
            AZUtils.printObject(response.body());
        }

        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
});
OhhhThatVarun
  • 3,981
  • 2
  • 26
  • 49
Den Steve
  • 101