1

I'm trying to upload an image to the server using Retrofit2, but am very unsure on how to do so.

The documentation left me a bit confused and I have tried the solution mentioned here, but it did not work for me.

Here is the code snippet I'm currently using, which doesn't send anything to the server:

// Service
@Multipart
@POST("0.1/gallery/{galleryId}/addImage/")
Call<ResponseBody> addImage(@Path("galleryId") String galleryId, @Part MultipartBody.Part image);

//Call
MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<ResponseBody> call = service. addImage("1234567890", imagePart);

However, I'm able to do it just fine using Retrofit 1.9 with a TypedFile.

Am I doing something wrong or Retrofit2 has some issue with this sort of thing?

Community
  • 1
  • 1
Larpus
  • 301
  • 1
  • 3
  • 17

2 Answers2

3

I've struggled for a while with this to, I ended up with this solution to finally make it work... Hopes it helps:

Map<String, RequestBody> map = new HashMap<>();
map.put("Id",Utils.toRequestBody("0"));
map.put("Name",Utils.toRequestBody("example"));
String types = path.substring((path.length() - 3), (path.length()));

File file = new File(pathOfYourFile);
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
map.put("file\"; filename=\"cobalt." + types + "\"", fileBody);

Call<ResponseBody> call = greenServices.upload(map);

In the greenServices interface:

@Multipart
@POST(Constants.URL_UPLOAD)
Observable<Response<ResponseBody>> uploadNew(@PartMap Map<String, RequestBody> params);
Jaythaking
  • 2,200
  • 4
  • 25
  • 67
0

hi please check how we can send image in retrofit2.In form of part you need to send image and other data as well.

public interface ApiInterface {
    @Multipart
    @POST("0.1/gallery/{galleryId}/addImage/")
    Call<User> checkapi (@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();
    }
});

Thanks hope this will help you.

Saveen
  • 4,120
  • 14
  • 38
  • 41