Upload Image using Retrofit and PHP API

Viewed 394

I am trying to upload image with Retrofit API. My android code is like below

public interface FileUploadService {
    @Multipart
    @POST("upload.php")
    Single<ResponseBody> onFileUpload(@Part("username") RequestBody mUserName, @Part MultipartBody.Part file);
}

and PHP code is like below

<?php
$target_dir = "upload/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();

// Check if image file is a actual image or fake image
if (isset($_FILES["file"])) 
{
   if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name)) 
   {
     $success = true;
     $message = "Successfully Uploaded";
   }
   else 
   {
      $success = false;
      $message = "Error while uploading";
   }
}
else 
{
      $success = false;
      $message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);


?>

I am not getting any error in android side and its working fine but in server, I am getting error like below

PHP Notice:  Undefined index: file in line 3

Let me know what I am missing. Thanks!

1 Answers

In your server part code, you're expecting the field name to be file. I guess that while preparing multipart data in Android, you're not using the same name (file).

In your Activity/Fragment, the multipart data preparation code should look like below.

String fileName = "your file name with extension";
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part.createFormData("file", fileName, requestBody);
                            // ----^^^^--- look at the field name (first parameter)
Related