This is my PHP code to upload file:
<?php
$target_dir = "uploads/";
$rand = rand(0, 99999999);
$target_file_name = $target_dir .basename("$rand.png");
$response = array();
$postTest = $_POST["postTest"];
if (isset($_FILES["upload_file"]))
{
if (move_uploaded_file($_FILES["upload_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;
$response["postTestStatus"] = $postTestStatus;
$response["postTestMessage"] = $postTestMessage;
echo json_encode($response);
This is my Android code:
val file = File(imagePath)
val requestBody = RequestBody.create(MediaType.parse("*/*"), file)
val fileToUpload = MultipartBody.Part.createFormData("upload_file", file.name, requestBody)
val requestPOST = RequestBody.create(MediaType.parse("plain/text"), textToPost)
var call = webApiInterface.uploadFile(fileToUpload, requestPOST)
call.enqueue()...
When I am trying upload only file, all is ok. But when I upload file and POST value, I have got errors ( JSON from reponse isn't valid )
My PHP script when I trying POST value:
<?php
error_reporting(0);
$target_dir = "uploads/";
$rand = rand(0, 99999999);
$target_file_name = $target_dir .basename("$rand.png");
$response = array();
$postTest = $_POST["postTest"];
if (isset($_FILES["upload_file"]))
{
if (move_uploaded_file($_FILES["upload_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";
}
if(isset($postTest))
{
$postTestStatus = true;
$postTestMessage = $postTest;
}
else
{
$postTestStatus = false;
$postTestMessage = "Value isn't set";
}
$response["success"] = $success;
$response["message"] = $message;
$response["postTestStatus"] = $postTestStatus;
$response["postTestMessage"] = $postTestMessage;
echo json_encode($response);
?>
WEBApiInterface:
@Multipart
@POST("retrofit-example/multipartPOSTtest.php")
fun uploadFile(@Part file: MultipartBody.Part,
@Part("postTest") valForPOST: RequestBody): Call<FileResponse>
MainActivity:
val fileToUpload = MultipartBody.Part.createFormData("upload_file", file.name, requestBody)
val requestPOST = RequestBody.create(MediaType.parse("plain/text"), textToPost)
var call = webApiInterface.uploadFile(fileToUpload, requestPOST)
Am I doing it right ? I am learning how to use Retrofit. I am asking for your understanding
// First
@Multipart
@POST("retrofit-example/multipartPOSTtest.php")
fun uploadFile(@Part file: MultipartBody.Part): Call<FileResponse>
// Second
@Multipart
@POST("retrofit-example/multipartPOSTtest.php")
fun uploadFile(@Part file: MultipartBody.Part,
@Part("postTest") valForPOST: RequestBody): Call<FileResponse>
Response method: pastebin