Search code examples
androidretrofitmultipartretrofit2

What is the best way to send @Multipart file/bitmap and extra parameters with retrofit 2?


I have a helper class:

public class RequestPart {
    public static RequestBody createFromBitmap(Bitmap bitmap) {
        return RequestBody.create(MediaType.parse("image/png"), Utils.getBytes(bitmap));
    }

    public static RequestBody createFromObject(Object value) {
        return RequestBody.create(
                MediaType.parse("multipart/form-data"), String.valueOf(value));
    }

    public static Map<String, RequestBody> convertMap(Map<String, Object> map) {
        Map<String, RequestBody> result = new HashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() instanceof Bitmap) {
                result.put(entry.getKey(), createFromBitmap((Bitmap) entry.getValue()));
            } else {
                result.put(entry.getKey(), createFromObject(entry.getValue()));
            }
        }
        return result;
    }
}

I use it this way:

Map<String, Object> params = new HashMap<>();
params.put("profile[param1]", String);
params.put("profile[param1]", Object);
params.put("profile[param1]", int);
params.put("profile[param2]", Bitmap);
params.put("profile[param2]", Bitmap);

retrofitService.updateProfile(RequestPart.convertMap(params));

Retrofit:

@Multipart
@POST("api-patient/upload/something.json")
Call<User> uploadStateId(@PartMap Map<String, RequestBody> params);

I tried wrap only Bitmap parameters but when I send a String to server like @PartMap Map<String, String> params it wraps value in double quotes ""Value"" that's why I use RequestBody for all parametes.

Does any one know the better or simpler way to do this?


Solution

  • Hi Please refer below blog link to upload files in retrofit 2.0

    https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server

    It has good explanation with example code.