I try to upload an image from an Android App to a Django server using Retrofit 2 and OkHttp3.
For that, I used to create a RequestBody
instance using the following lines:
RequestBody requestImageFile =
// NOW this call is DEPRECATED
RequestBody.create(
MediaType.parse("image/*"),
// a File instance created via the path string to the image
imageFile
);
I used the previous instance in the next method call as argument:
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part image = MultipartBody.Part.createFormData("image", imageFile.getName(), requestImageFile);
Finally, I fired up the Retrofit interface to do the rest:
// finally, execute the request
Call<ResponseBody> call = service.upload(image);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.v("Upload", "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
Some months ago, Android Studio did not told me that create()
was deprecated. When I open the project now, it tells me that create()
is deprecated. Does somebody know how to fix it ?
Just swap the parameters from
RequestBody.create(MediaType.parse("image/*"), imageFile);
to
RequestBody.create(imageFile, MediaType.parse("image/*"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With