I want to upload the image to the server.
- I got the bitmap of the image and encoded it to base64.
- I convert the base64 of the image to a string using the encodeToString method.
- I post the string to PHP using httpurlconnection. Actually, I got the string from PHP which is not the whole string. I don`t get any error. Please give me feedback!
public String httpURLConnectionPost(final String urlString){
String result="";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.download);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.NO_CLOSE);
String body= "image="+encodedImage;
Log.d("serverPostData","body = " +body);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(body);
writer.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
stringBuilder .append(line);
}
result = stringBuilder .toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
The php got the string and decode it.
<?php
include("mysqli_connect.php");
$image= $_POST['image'];
$a = uniqid() ;
$ImagePath = "good/$a.JPEG";
$ServerURL = "https://172.30.10.1/$ImagePath";
$InsertSQL = "INSERT INTO Photoshop(photo) VALUES('$ServerURL')" ;
if(mysqli_query($connect, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($image));
echo $image;
}else{
echo "failed";
}
mysqli_close();
?>
2
Answers
I solved my probelm that the base64 need to replace empty to "+".
Try this to convert image to base64:
Now pass the data in API:
Now set ImageBitmap:
Here is the method:
And for HttpUrlConnection try this…
Hope this one will work for you…