Is it possible to pass one element as multipart using modification?

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

      

I only want to send the image as multi-page and the rest as is. Is there any possible way? Even I tried to add TypedFile inside my Deal model but couldn't comment @part

+3


source to share


3 answers


Yes it is possible with Partmap annotation using hashmap. For example -

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

      

In hashMap you can add any url parameters as key and set your values ​​using RequestBody class type. 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 parameters 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 it helps.

+2


source


It seems that you can send your @Body as TypedString.
For example, convert the transaction "@Body Deal" to a JSON String and send it as a TypedString.

Details: How to submit multipart / form data using Retrofit?



@Multipart
@POST("/api/v1/articles/")
Observable<Response> uploadFile(@Part("author") TypedString authorString,
                                @Part("photo") TypedFile photoFile);

      

0


source


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();
        }
});

      

0


source







All Articles