Android post Base64 String to PHP
Solution 1
This is the code for image:
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
This is the HTTP code for sending the image to the server:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://servername.com/uploadimage.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
If you find any more difficulties ask me or a check:
In PHP header file changes :
header('Content-Type: image/jpg; charset=utf-8');
$base=$_REQUEST['image'];
Solution 2
Is the HTTP-Response-Code you are getting 200? If so, try setting these header-fields:
"Accept": "text/html"
"Accept-Language": "en"
"Content-Length": yourString.length
"Content-Type": "application/x-www-form-urlencoded"
Solution 3
Try sending your data as below:
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 60000); //1 min
HttpConnectionParams.setSoTimeout(httpParams, 60000); //1 min
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost("http://myURL/uploadImage.php");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("image", image_str));
post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)); // as UTF-8
HttpResponse response = client.execute(post);
Solution 4
just download the Base64.java http://iharder.sourceforge.net/current/java/base64/ & put that file in your project & then
just replace the
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
this with
String image_str = Base64.encodeBytes(byte_arr);
replace this post.setEntity(new UrlEncodedFormEntity(pairs));
with
post.setEntity(new UrlEncodedFormEntity(pairs,HTTP.UTF_8));
Also check while importing the Base64 it will import file from your package & then post to server it will post.
in your php code just change
change this
$base = $_POST["image"];
to
$base = $_REQUEST['image'];
Solution 5
Have you tried reading the raw post data in PHP? Something like
$data = $xml = file_get_contents('php://input');
Have a look at this link for more info
Related videos on Youtube
PinkFloydRocks
iPhone novice - getting there one line at a time :-)
Updated on September 11, 2020Comments
-
PinkFloydRocks over 3 years
------ Solution ------
The issue was on our server. It can only handle post requests if we put www in front of our domain name. So that's what caused the problems. I'm setting the first answer as THE answer since it worked once I sorted the URL out.
Original Question
I have a POST variable in my PHP script is always blank.
I've tried to change the variable's name, the content of the variable etc..The problem has to reside in the java code, because when I
var_dump()
the request in php, it is null.This is my scenario:
I let the user snap a photo, the photo is saved to the SD-card and I get the image's path, and eventually convert it to a Base64 string. I then want to post this base64 string to a php script that converts it back from Base64 and writes it as an image on my server's hard drive like so:
File f = new File(savedImagePath); Bitmap bitmap = BitmapFactory.decodeFile(f.getPath()); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 30, stream); byte [] byte_arr = stream.toByteArray(); String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://myURL/uploadImage.php"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("image", image_str)); post.setEntity(new UrlEncodedFormEntity(pairs)); HttpResponse response = client.execute(post);
On the server end, this is what my PHP script looks like:
<?php $base = $_POST["image"]; $binary=base64_decode($base); header('Content-Type: bitmap; charset=utf-8'); $file = fopen('uploaded_image.jpg', 'w'); fwrite($file, $binary); fclose($file); echo "script done executing"; ?>
This is an example of a Base64 string I'm trying to post:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABsSFBcUERsXFhceHBsgKEIrKCUlKFE6PTBCYFVlZF9VXVtqeJmBanGQc1tdhbWGkJ6jq62rZ4C8ybqmx5moq6T/2wBDARweHigjKE4rK06kbl1upKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKT/wAARCAogBsADASIAA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UxMO/NLSA55o6nrQMP1pfejFHWgA96B0pPalPXHFFhBRnik+lLQOwZ5o6UdKM/jQAoo70maO1AhT1pMcUg5pc0D0F70daT3paBAKKM0UDYDrSj+dJSigVw70d6QUtAw9zzRSZpc5+tMVwNL7UlH40gCgdaUcUlMApRRR2oAPeiijPFAIBQOtFFAbCikozRQADmlpBS0DAUUnfNL3oEFAo7YoxTAXvSdqO+BzR9KAClHWkooBB0paM0UgFpBSdTQPrmgQtHWjPOaO9MBc0Ug60A0guFLRSUDQUUfSimAtJ3oo70gFzRSUZoAWkozR+lMOgtFJR1oAXNHSkFFAC0dqQdKM0gFopB15oPWmAtA60maO1AIWj8KQUUBYX9aKQGigA9qKM0d6QCig0lFAgo60DpRQMO1ITRmk7UCEprdKcaQ0DGGoyKeaY3ftSAYSKhbpUp7d6jbmkxoiPFN7U5vu9aYeKQx38OR0pU9qb29q
-
Andreas Wong about 12 yearsare you using android emulator? See if there's any network analyzer to make sure that "image" is indeed get sent out
-
PinkFloydRocks about 12 yearsNo, I'm testing on a HTC Wildfire at the moment. I'm using eclipse, is there a built in network analyzer or do I have to do some searching on the web?
-
Rizvan about 12 years@PinkFloydRocks Problem occur a lot in this case .. if you have any more query ask here
-
Rizvan about 12 years@PinkFloydRocks i got your mistake listen just add header('Content-Type: image/jpg; charset=utf-8'); sure you will get
-
PinkFloydRocks about 12 years@TinTin I've tried editing the header as you proposed but still no luck.. Think I'm just going to close my eyes and hope that the magical debug fairy pays me a visit and fixes everything... Ah, that's better! ;)
-
Rizvan about 12 years@PinkFloydRocks can u tell me what is reply from server
-
PinkFloydRocks about 12 years@TinTin the reply from the server is just what is being echoed: "script done executing"
-
Rizvan about 12 years@PinkFloydRocks look instead of echo string .. echo image ok ........... echo "<img src='upload_image.jpg'>"; check it tell what reply u got .. i can help u further
-
PinkFloydRocks about 12 yearsNow it just echoed <img src='upload_image.jpg'>
-
Rizvan about 12 years@PinkFloydRocks dude use this one echo "<img src=uploadimage.jpg>";
-
PinkFloydRocks about 12 years@TinTin same result as the last echo I'm afraid
-
-
PinkFloydRocks about 12 yearsStill no luck. It's probably worth mentioning that when I changed the $base variable in the php to get its data via $_REQUEST['image'] and I looked up the URL in my web browser, the data in the ?image= variable did get written to the file.
-
quickshiftin about 12 yearsHave you looked at the request with something like tcpmon? An easier way to start would be to just
var_dump($_REQUEST);
to see what you're working with in PHP. Another sanity check option would be to check$_SERVER['REQUEST_METHOD']
but it probly is POST... You can actually send GET data along w/ a POST request as well, not sure how the GET params are being set from your code sample, but in general I would recommend determining whether certain variables are coming from GET or POST and coding against that.$_REQUEST
is more or less for debugging. -
PinkFloydRocks about 12 yearsHi, I've tried your solution before, but it didn't work for me. It's really frustrating.. Thanks for your answer though.
-
PinkFloydRocks about 12 yearsSorry, no luck with this solution.. It definitely looks like the POST data isn't reaching my php script by some terribly odd reason..
-
Rizvan about 12 years@PinkFloydRocks Have u tried php code changes what i written ?
-
PinkFloydRocks about 12 yearsJust ran the $_SERVER['REQUEST_METHOD'] and it says GET!! Is this the source of all my problems?
-
PinkFloydRocks about 12 yearsChanged to $_REQUEST[] but no luck now either
-
PinkFloydRocks about 12 yearsYeah, unfortunately no solution.. Sorry
-
PinkFloydRocks about 12 yearsI tried implementing a GET request (HttpGet instead of HttpPost) to the server in stead and the data is actually being sent, but I get an error (414 URI too large) and that's of course because of the length of the Base64 string. Know of a way to post large strings via GET?
-
waqaslam about 12 yearsone thing, is this
http://myURL/uploadImage.php
you purposely made? confirm if you aren't using it mistakenly :) -
PinkFloydRocks about 12 yearsyeah - wish it was that simple :-) I'll give your approach a try - thanks!
-
PinkFloydRocks about 12 yearsWow... I just spoke to one of our server guys, and the problem was actually related to what your comment was about.. I had to use www in front of our domain name with post requests... Wow... I'm going to upvote your answer but I can't give you the answer since all the examples are now working. But THANKS!
-
quickshiftin about 12 yearsI would try to avoid sending large amounts of data over GET and figure out how to send over POST from the android. Glad to hear we uncovered something of the issue though!