I am trying to upload image from my android application to a php server but I can't seem to make it work.
The image is being converted to a string, as i have tried displaying it in a textview. The image also uploads to the server successfully but first the image size is 0.1kb.
I have tried all kinds of image and the image is not displaying. So I think the problem is with the php code.
Here is the php code I am using:
<?php
$target_dir = "User Images";
$image = $_POST["image"];
if(!file_exists($target_dir)){
mkdir($target_dir, 0777, true);
}
$target_dir = $target_dir ."/". rand() . "_". time() . ".jpeg";
if(file_put_contents($target_dir, base64_decode($image))) {
echo json_encode([
"Message" => "Saved",
"Status" => "Ok"
]);
} else{
echo json_encode([
"Message" => "FAILED",
"Status" => "Error"
]);
}
?>
Here is the code am using to upload the file to the server
url = "MY URL";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> {
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
}, error -> {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}){
@Override
protected Map<String, String> getParams()throws AuthFailureError{
Map<String, String> params =new HashMap<>();
String imageData = imageToString(bitmap);
params.put("image", imageData);
return super.getParams();
}
};
requestQueue.add(stringRequest);
And the code to convert the image to string
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imgBytes = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgBytes, Base64.DEFAULT);
Any help will be greatly appreciated