Reputation: 853
first, of all i tried to follow this question but it doesn't works.
I have to call an API and send an image and a user name in the body, i do have called the APIs before using the retrofit but i have no idea how to send an image now.
here is my code as of now
private fun uploadProfileToDashboard(path: String) {
var aes = Utils.getPref(
requireContext(),
Constants.ENCRYPTION_AES,
"x"
)!!
var iv = Utils.getPref(
requireContext(),
Constants.ENCRYPTION_IV,
"x"
)!!
val file: File = File(path)
val fbody = RequestBody.create(
"image/*".toMediaTypeOrNull(),
file
)
profileViewModel.updateProfilePicInDashboard(
mapOf(
"object_id" to Utils.getPref(
requireContext(),
Constants.ENCRYPTION_OBJ_ID,
"x"
)!!,
"db_name" to Utils.getPref(
requireContext(),
Constants.PROVIDER_NAME,
"x"
)!!
),
AESEncryption(
aes,
iv
).encrypt(profile.dashboardUserName)!!,
fbody
)
}
fun updateProfilePicInDashboard(
headerParams: Map<String, String>,
user_id: String,
image: RequestBody
) {
val call = RetrofitClient.updateProfilePicInDashboard.updateProfilePic(headerParams , user_id , image)
call.enqueue(object : Callback<UserProfilePicResponceModal> {
override fun onResponse(
call: Call<UserProfilePicResponceModal>,
response: Response<UserProfilePicResponceModal>
) {
Log.i("here22" , response.body().toString())
}
override fun onFailure(call: Call<UserProfilePicResponceModal>, t: Throwable) {
Log.i("here22" , t.message.toString())
}
})
}
@Multipart
@FormUrlEncoded
@POST("/index.php/Profile/editProfile")
fun updateProfilePic(
@HeaderMap headers: Map<String, String>,
@Part("user_id") userId: String,
@Part("file\"; filename=\"pp.png\" ") userfile: RequestBody
) : Call<UserProfilePicResponceModal>
But this does work, it fire an error -> Failure delivering result ResultInfo{who=null, request=67940, result=-1, data=Intent
Upvotes: 0
Views: 849
Reputation: 544
you can use RequestBody for sending images and data to API.
For Ex:
Java
@POST("End_point_of_api")
Call<Response> doUpdateProfileDetails(
@Body RequestBody requestBody
);
kotlin
@POST("End_point_of_api")
fun doUpdateProfileDetails(
@Body RequestBody requestBody
) : Call<Response>
And call above API as follow:
Java
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
builder.addFormDataPart("userName", "user123");
builder.addFormDataPart("userPhoto", "file_name", RequestBody.create(MultipartBody.FORM, new File("path")));
RequestBody requestBody = builder.build();
// call api here and pass requestBody as a parameter.
kotlin
val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
builder.addFormDataPart("userName", "user123")
builder.addFormDataPart("userPhoto", "file_name", RequestBody.create(MultipartBody.FORM, File("path")))
val requestBody: RequestBody = builder.build()
// call api here and pass requestBody as a parameter.
Upvotes: 2