Image File Not Going To Server Using Retrofit 2 Post Method
Hi friends please help me out here i am new for the retrofit i am trying use the post method in the retrofit to send the image file by converting it into base64 format but it is no
Solution 1:
In order to POST a file, we need to enable Multipart
.Part
define a part inside the Multipart
. MultipartBody.Part
is the type that we want to use for a file / image. Non-file Part should use RequestBody
type with expected fieldname
Service / Endpoint interface
interfaceService {
@Multipart@POST("/")
Call<ResponseBody> postImage(@Part MultipartBody.Part image, @Part("name") RequestBody name);
}
Retrofit call, postImage parameter
Filefile=newFile(filePath);
RequestBodyreqFile= RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Partbody= MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
RequestBodyname= RequestBody.create(MediaType.parse("text/plain"), "upload_test");
retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body, name);
req.enqueue(newCallback<ResponseBody>() {
@OverridepublicvoidonResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
// Do Something
}
@OverridepublicvoidonFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
Go through this githib example for more details
EDIT
Parameters along with Image would be as follows
@Multipart@POST("users/{id}/user_photos")
Call<models.UploadResponse> postImage(@Path("id") int userId, @PartMap Map<String, RequestBody> params);
Request parameters
//All the String parameters
Map<String, RequestBody> map = newHashMap<>();
map.put("methodName", toRequestBody(methodName));
map.put("userid", toRequestBody(userId));
map.put("name", toRequestBody(name));
//To put your image file as wellFilefile=newFile("file_name");
RequestBodyfileBody= RequestBody.create(MediaType.parse("image/png"), file);
map.put("relative_image\"; filename=\"some_file_name.png\"", fileBody);
// This method converts String to RequestBodypublicstatic RequestBody toRequestBody(String value) {
RequestBodybody= RequestBody.create(MediaType.parse("text/plain"), value);
return body ;
}
//To send your request
call = service.postImage(body, params);
Post a Comment for "Image File Not Going To Server Using Retrofit 2 Post Method"