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 ?
import okhttp3.RequestBody.Companion.toRequestBody
in the import section of your Kotlin file. 2. change code toimageFile.asRequest("image/*")
for file type, or if you have some other content (string, for example), then usecontent.toRequestType(mediaType)
– Sublimate