I am trying to upload an image through API call from my app. But it seems to me that it is working in postman but not when done through my app. I am using retrofit 2 and backend code is PHP.Kindly help me through the process.
PHP Code:
case 'profileImage':
$id=$_POST['id'];
$image_name=("profile".$id.".jpg");
$upload_path=("../gm-app/assets/images/users-profile/".$image_name);
$res= mysqli_query($db,"UPDATE `users` SET `image` = ('$image_name') WHERE `userid`='".$_POST['id']."'");
if(isset($_FILES['file'])){
if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)){
$rs['message'] = "Profile Image Updated";
$rs['stat'] = "SUCCESS";
}else{
$rs['message'] = "Profile Image not Updated";
$rs['stat'] = "FAILED";
}
}
echo json_encode($rs);die;
break;
Retrofit call:
File file = new File(mediaPath);
RequestBody requestBody=RequestBody.create(MediaType.parse("image/*"), file);
Retrofit retrofit=new Retrofit.Builder().
baseUrl(MyConstants.ROOT_URL).
addConverterFactory(ScalarsConverterFactory.create()).
build();
apinterface services = retrofit.create(apinterface.class);
Call<ResponseBody> call=services.postImage(requestBody,uid);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.body()!=null)
{
try {
Toast.makeText(MyProfile.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
String image = response.body().string();
Log.d(TAG, "onResponse: "+image);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d(TAG, "onFailure: "+t.getMessage());
}
});
API :
@Multipart
@POST("services.php?apicall=profileImage")
Call<ResponseBody> postImage(@Part("file") RequestBody image, @Part("id") String id);
Because there's something wrong with your code about multipart..
Interface :
@Multipart
@POST("services.php?apicall=profileImage")
Call<ResponseBody> postImage(
@Part MultipartBody.Part image,
@Part("id") RequestBody id
);
Call the API
Retrofit retrofit=new Retrofit.Builder().
baseUrl(MyConstants.ROOT_URL).
addConverterFactory(ScalarsConverterFactory.create()).
build();
apinterface services = retrofit.create(apinterface.class);
//Bikin request body
File file = new File(mediaPath);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
RequestBody reqId = RequestBody.create(MediaType.parse("text/plain"), uid);
//Tembak APInya
services.postImage(reqfile, reqId)
.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//tulis aksi disini
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//tulis aksi disini
}
});