Android image upload not getting to PHP script - php

I'm trying to upload an image from Android to a PHP server.
Here is my upload code:
public static void uploadFile(final String imagePath){
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER);
try {
File imageFile = new File(imagePath);
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("image", new FileBody(imageFile));
httpPost.setEntity(entity.build());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Here is my PHP code for handling the upload:
<?php
echo "FILES - ";
var_dump($_FILES);
echo " REQUEST - ";
var_dump($_REQUEST);
$file_path = "images";
$file_path = $file_path . basename($_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
I'm getting 200 responses from the page, but the $_FILES and $_REQUEST variables are both empty. It seems that the image file is not making it to the script, and I have no idea why. I'm doing it right according to all the tutorials I've found.
The images I'm uploading are ~180kb
Any ideas?

This was a problem with my server. I switched to using a different sub-domain of my server, and it's working perfectly now.

Related

How to display an image from mysql php into android?

I am currently trying to display an image from mysql database into my android program using an image view. However, it does not work the way I wanted to yet. The following is the php code i currently have:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
require 'connect_aircraftoperator.php';
$image = $db->query("SELECT companyImage FROM company where companyID = 2");
$getImage = $image->fetch_assoc();
$upload = $getImage['companyImage'];
header("Content-type: image/png");
echo $upload;
?>
The code displays the image just fine in the browser. The following is my current android code
void getImage() {
//String imageResult = "";
//JSONObject jArray = null;
//String Qrimage;
//Bitmap bmp;
try {
//setting up the default http client
HttpClient httpClient = new DefaultHttpClient();
//specify the url and the name of the php file that we are going to use
//as a parameter to the HttpPost method
HttpPost httpPost = new HttpPost("http://10.0.2.2//aircraftoperatorapp/leimage.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e) {
System.out.println("Exception 1 Caught ");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//create a string builder object to hold data
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
//use the toString() method to get the data in the result
imageResult = sb.toString();
is.close();
//checks the data by printing the result in the logcat
System.out.println("---Here's my data---");
System.out.println(imageResult);
}
catch (Exception e){
System.out.println("Exception 2 Caught ");
}
try {
//creates json array
JSONArray jArray = new JSONArray(imageResult);
for (int i = 0; i < jArray.length(); i++)
{
//create a json object to extract the data
JSONObject json_data = jArray.getJSONObject(i);
imageTemp = json_data.getString("companyImage"); //gets the value from the php
}
lblTesting3.setText(imageTemp);
byte[] data = Base64.decode(imageTemp, 0);
Bitmap b = BitmapFactory.decodeByteArray(data,0,data.length,null);
imgCompany.setImageBitmap(b);
}
catch (Exception e){
//System.out.println("Exception 3 Caught ");
Log.e("lag_tag", "Error Parsing Data " + e.toString());
}
}
All I have returning is some text that probably has to do with the image I'm returning. The following text is like this in the beginning:
ÿØÿáhExifMM*vž¤¬(1´2Ò‡iè ü€' ü€..... and so on.
Is there a way I can convert this into an image that is displayable into my android program with the code I have or do I have to do something more different? I would appreciate anyone would help me! It would mean a lot! Thanks in advance!
I think the issue you're facing with is a simple decoding mistake.
HttpEntity entity = response.getEntity();
is = entity.getContent();
The InputStream you're getting from the HttpEntity contains binary image data. So you can simply copy that data into an bytearray:
...
Bitmap bitmap;
byte[] image = null;
...
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out, true);
image = out.toByteArray();
in.close();
bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
...
public static void copy(InputStream in, OutputStream out, boolean close)
throws IOException
{
if (in != null && out != null)
{
byte[] buffer = new byte[4096];
int count;
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count);
if (close)
{
in.close();
out.close();
}
}
}

empty $_POST and $_FILES with request type multipart/form-data

I'm trying to send post request from android application to server. In this request I want to send some text data (json) and picture.
But I can't get this data in server. Variables $_FILES, $_POST and even php://input is empty. But data is really transferred to server, because in $_SERVER I can find this:
[REQUEST_METHOD] => POST
[CONTENT_TYPE] => multipart/form-data; boundary=Jq7oHbmwRy8793I27R3bjnmZv9OQ_Ykn8po6aNBj; charset=UTF-8
[CONTENT_LENGTH] => 53228
What is the problem can be with this?
server is nginx 1.1
PHP Version 5.3.6-13ubuntu3.10
file_uploads = On
Here is my android code
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(30000)
.setConnectionRequestTimeout(30000)
.setSocketTimeout(30000)
.setProxy(getProxy())
.build();
CloseableHttpClient client = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.build();
HttpPost post = new HttpPost("http://example.com");
try {
JSONObject root = new JSONObject();
root.put("id", id);
if (mSettings != null) {
root.put("settings", SettingsJsonRequestHelper.getSettingsJson(mSettings));
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File screenshot = getScreenshotFile();
if (screenshot.exists()) {
builder.addPart("screenshot", new FileBody(screenshot, ContentType.create("image/jpeg")));
}
builder.addTextBody("data", root.toString(), ContentType.create("text/json", Charset.forName("UTF-8")));
builder.setCharset(MIME.UTF8_CHARSET);
post.setEntity(builder.build());
} catch (JSONException e) {
Logger.getInstance().log(e);
}
try {
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
mResponse.setResponse(response.getEntity().getContent());
} else {
Logger.getInstance().log("response error. Code " + response.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
Logger.getInstance().log(e);
} catch (IOException e) {
Logger.getInstance().log(e);
}
Maybe you have te change php.ini parameters like enable_post_data_reading=on increase post_max_size and upload_max_filesize
Not sure of the method you are using and you did not include your server side processing file. Error may be from either one. But try this. I first send it a file path through the params and named it 'textFileName'.
#Override
protected String doInBackground(String... params) {
// File path
String textFileName = params[0];
String message = "This is a multipart post";
String result =" ";
//Set up server side script file to process it
HttpPost post = new HttpPost("http://10.0.2.2/test/upload_file_test.php");
File file = new File(textFileName);
//add image file and text to builder
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("uploaded_file", file, ContentType.DEFAULT_BINARY, textFileName);
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
//enclose in an entity and execute, get result
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return message;
}
Server side php looks like:
<?php
$target_path1 = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$status = "";
if(isset($_FILES["uploaded_file"])){
echo "Files exists!!";
// if(isset($_POST["text"])){
// echo "The message files exists! ".$_POST["text"];
// }
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
$status= "The first file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded.";
}
else{
$status= "There was an error uploading the file, please try again!";
$status.= "filename: " . basename( $_FILES['uploaded_file']['name']);
$status.= "target_path: " .$target_path1;
}
}else{
echo "Nothing in files directory";
}
$array["status"] = "status: ".$status;
$json_object = json_encode($array);
echo $json_object;
?>

Upload/download Image issue android + PHP + Base64

hello there I have an issue with displaying an image on an imageButton that I uploaded to my server. I can't figure out what is my mistake !
here is a short idea for what I'm doing when uploading :
Bitmap Image -> Base64 encoded to string -> upload string to server -> write string to file
a short idea for what I'mg doing when downloading:
read string from file -> put in JSON -> receive in Android -> Base64 decode to byte array-> decode byte array to Bitmap -> post to ImageButton
java code:
//Storing image string
if(scaledBitmap == null){
bitMapPartyPicture = ((BitmapDrawable)partyPicture.getDrawable()).getBitmap();
}else{
bitMapPartyPicture = scaledBitmap;
}
String imageString = jsonParser.encodeImage(bitMapPartyPicture);
//Encoding the Image
public String encodeImage(Bitmap image){
Bitmap bitmap = image;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte [] byte_arr = stream.toByteArray();
Log.d("Image Base64",stream.toString());
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
return image_str;
}
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
//Upload Image
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://whatever.com/addProfilePic.php");
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
is.reset();
is.close();
}catch(Exception e){
System.out.println("Error in http connection "+e.toString());
}
//Dealing with JSON Object
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
Log.d("JSON Object", json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
//Download Image
public byte[] downloadImage(String url,List<NameValuePair> imgName) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] ImageBytes = new byte[1024];
String ImageString = null;
byte[] DecodedImage = new byte[1024];
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(imgName));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
int LinesValue = 0;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
LinesValue++;
}
json = sb.toString();
Log.d("Lines",Integer.toString(LinesValue));
Log.d("JSON Object", json);
jObj = new JSONObject(json);
ImageString = jObj.getString("Image_Decoded");
ImageBytes = ImageString.getBytes(Charset.forName("UTF-8"));
is.close();
}
catch(IOException t) {
t.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DecodedImage = Base64.decode(ImageString ,Base64.DEFAULT);
return DecodedImage;
}
PHP Uploading side:
$image = $_POST['image'];// name of uploaded image
$user = $_POST['user'];
$image_name = $_POST['imageName'];
$file = null;
$filePath = "photos/" . $user;
$homeDir = "/home/a1400606/public_html/";
if (!file_exists($homeDir.$filePath)) {
mkdir($filePath, 0777);
}
if($image_name == 'partyPicture'){
$file = fopen('partyPicture', 'w');
fwrite($file, $image);
fclose($file);
}else if ($image_name == 'profilePicture'){
$file = fopen('profilePicture', 'w');
fwrite($file, $image);
fclose($file);
}else{
$response["Error:"] = "Error";
}
if(rename(addslashes("$homeDir"."partyPicture"),addslashes( "$homeDir$filePath"."/partyPicture"))){
$response["File Moved:"] = "Yes";
}else {
$response["File Moved:"] = "No";
}
PHP Downloading side:
$image = "partyPicture";// name of uploaded image
$user = "xxxx";
$filePath = "photos/" . $user."/";
$homeDir = "/home/a1400606/public_html/";
if (!file_exists(addslashes($homeDir.$filePath.$image))) {
$response["Found File"] = "File doesn't exist";
}else{
$response["Found File"] = "File exist in directory";
$imgstr=fread(fopen($homeDir.$filePath.$image,"r"),filesize($homeDir.$filePath.$image));
$response["Image_Decoded"] = $imgstr;
}
echo json_encode($response);
Posting image to ImageButton:
byte[] bytesArray = new byte[1024];
bytesArray = json.downloadImage(DOWNLOAD_IMAGE_URL, params);
ImageBitmap = BitmapFactory.decodeByteArray(bytesArray, 0,bytesArray.length);
if(ImageBitmap == null){
InputStream is= new ByteArrayInputStream(bytesArray);
ImageBitmap = BitmapFactory.decodeStream(is);
}
CreateImageBitmap = Bitmap.createBitmap(ImageBitmap);
catLog for Uploading:
05-22 00:29:43.874: D/Image Base64(7530): ??????JFIF????????????????C??????C????p0"??????????????????????????
05-22 00:29:43.874: D/Image Base64(7530): ???????????}??!1AQa"q2???#B??R??$3br?
05-22 00:29:43.874: D/Image Base64(7530): %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz???????????????????????????????????????????????????????????????????????????????????????????
05-22 00:29:43.874: D/Image Base64(7530): ?????????w??!1AQaq"2?B???? #3R?br?
05-22 00:29:43.874: D/Image Base64(7530): $4?%?&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz?????????????????????????????????????????????????????????????????????????????????????{<1$?'?r_?O]???`????(,J?_?:?8?R;S????#????????Uy]?lU?FN?s??O??n???? E?gk?:I???S?eI?K?^>???V??~??o??A??$g????s?8?$?k??e?
?>e?~?Ons?g=A#?d?rD??6?1?#'???9??????j?^U?%???I???~?????r?F?????m????_]|?W$????v???E?&?w??zl??=?w3?x?M??QlA$???89??????1o"?Je`????y??}3?=??:??%??0%?c??? ?NFsY?q?D?,RQwI?{?]5???cw}O??$$?2??t???z]??[??hs-?mA??pH??b?C?????W?????$?G.$?????r9??[\Gg<A?v#&??Q?+?$`??n? ?^????A{??o????
05-22 00:29:43.874: D/Image Base64(7530): Ibs?#??>lj????'h?Z2\???}?V???B?9?9???Z&?U??-??x??{???<^??YA?6????\?V??U&ge??r[????'?CWmu??\y?A#?1o??I?B????$??u???^?ti>?:??(??{pS?O?Ms?E????????o?n??NthQ?????K???Z??????>???? ?p?z{??yl??$?X?*\H???t96~?#?-\k2??q}:???G??Sk:?z?x?rI??????r???v?`?y??9??e? 9VvW?m???r??????a9jNrVR?6?g)>f?n???k?4??$?1???g??'$?.?$U=0?;?>???tq?z??n???_S?lc ?????9-?K?$a????9?L~??^?,????IY-uWVM???K=[J???S??r?:i?Y^???????j?Wi$n??BG^XpA?P3?y??'???]NP?
?A??x??????,J?8u%?.?G_|{??&'<?9?????}J?$???kF?ww????%m???S?????????????????\?F=?I;H?=9???5??j??G?n??K7a???y!N}9??????$`?|z?'?p??w?????(?9??8??'????J??Vzn?{O7????B??)k?\???D?????{$./???????c?hk??\c?V?y?=3??3?.>P9????_? ?5v?$I
???`??z?:??I&????(?(%??G???Os????v?Q_?4????u??h?8??f)??px?\~G???kU??FDd??,?8?=3?p20
_??H??;[????}y??O$f?Ymf.???o?N??I???o?
05-22 00:29:43.874: D/Image Base64(7530): ????n|?o????????]??fn?fbF9??[8?? ??]B?]HnH?#i9?^?????????? ?}??t?=??v??*??S?Ts?9?}3?;????T?|??[E??????Wf??g Mj?IZ???}??}t????Z`e?99??z??????5?!??&p2x???<????$?$
05-22 00:29:43.874: D/Image Base64(7530): ???|?Q???)-???????lc3:?0???N2zq??O??pZ?_??%4?i?/]?iwV?????;?????+?????
05-22 00:29:44.134: D/Address(7530): 567 Beaverbrook Ct
05-22 00:29:44.134: D/PostalCode(7530): E3B
05-22 00:29:44.134: D/City(7530): Fredericton
05-22 00:29:44.134: D/Date Format(7530): 22-5-2014
05-22 00:29:44.134: D/StartDate(7530): 22-5-2014
05-22 00:29:44.134: D/EndDate(7530): 22-5-2014
05-22 00:29:44.134: D/GeoAddress(7530): [Address[addressLines=[0:"567 Beaverbrook Ct",1:"Fredericton, NB E3B",2:"Canada"],feature=567,admin=New Brunswick,sub-admin=null,locality=Fredericton,thoroughfare=Beaverbrook Ct,postalCode=E3B,countryCode=CA,countryName=Canada,hasLatitude=true,latitude=45.9537013,hasLongitude=true,longitude=-66.646423,phone=null,url=null,extras=null]]
05-22 00:29:44.754: I/Choreographer(7530): Skipped 75 frames! The application may be doing too much work on its main thread.
05-22 00:29:46.614: I/System.out(7530): Error in http connection java.io.IOException
05-22 00:29:48.874: D/JSON Object(7530): {"File Moved:":"Yes","ImageString":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH\/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH\/wAARCAVwAzADASIA\nAhEBAxEB\/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL\/8QAtRAAAgEDAwIEAwUFBAQA\nAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3\nODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm\np6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6\/8QAHwEA\nAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL\/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx\nBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK\nU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3\nuLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6\/9oADAMBAAIRAxEAPwD8+ns8\nMSQeoyeecl+2T12\/+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yc\nnpnAJPK5JAr6v8S2h3y7DlGBBO3kKS3JGevT8xyMFq8M12xjMzrkMAOrAE4yenHQ\/U\/w8HBanl+P\nnCU0k2nKL13vaXdW1sr\/ADvdpoiliqkrqK\/l6+bSbu\/K1n53u02\/nu\/s5ZQ8jA5wByOdoJxnnocf\nnxng54G8h2yyJjkEAjnsznOCCc\/KD\/jyT75rlnBBA4VuqIcbQBnLg8598+\/Qk5Brxi8SN55XHLBs\nhdo5G5u\/b7vP\/wBevvslqe1jUm3q05tOyeyvp9781bzZ6eEvL2nPvJR5vxv1\/wCDq9d75trO1qN6\njPPAJ+YckdcdO59iOu3JR\/EEwmeFYyQAuCcjOdxPQn0PXqcckgE3lgEhJYfp6Z98DOOn68jMH2eL\nzmURBiCOScEgA4P0749+TjNdc6MpTlJ6Ra0ej15pW05r7c3463sdPsaaVrr7n\/8AI+vTq9Wya21K\nRpA7Lwc4GT\/tYx\/3yMnP8QHUZPoHh3WljcB2A4H1U\/MOOent659SRxkcMUMbSSKFVR6cEksBznjq\nfoQRk4yYrO6SS4eO3wTu4GSMncRkgHnjd055PJIOeGvgYVVLVuVoxfu9OaXdtfjs1q2nfnrUacou\nKdmktk0muae7aWvVa230tzH2r8Mta+3XiQMD5aNGoZeRt3Hoec5xyD149cn9OPhsukTaXHAWCt5a\nMfm5IBfnjnkAdTj5eoLEV+WnwPjC3NqLuMRK\/lfP3J8wAn5h246+o6Hk\/qJ4N0wRWcEtrhomCK0u\nQMKSxxwTySM\/XPOGc18XPJaSqVXDWfPNxT0XNzz6t6bJ\/erO0m+fBYaLc1HV81rdb3kn0s+yt1T6\nx195tdJsLWH7TCwYkDI5ORlvm7+o6\/mSWrUh0+61JlR1IjAXaSMZG5sZ59APXqMn
Catlog for Downloading:
05-22 00:30:58.664: D/Lines(7530): 1
05-22 00:30:58.694: D/JSON Object(7530): {"Found File":"File exist in directory","Image_Decoded":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDAAEBAQEBAQEBAQEBA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i8SN55XHLBs\nhdo5G5u\/b7vP\/wBevvslqe1jUm3q05tOyeyvp9781bzZ6eEvL2nPvJR5vxv1\/wCDq9d75trO1qN6\njPPAJ+YckdcdO59iOu3JR\/EEwmeFYyQAuCcjOdxPQn0PXqcckgE3lgEhJYfp6Z98DOOn68jMH2eL\nzmURBiCOScEgA4P0749+TjNdc6MpTlJ6Ra0ej15pW05r7c3463sdPsaaVrr7n\/8AI+vTq9Wya21K\nRpA7Lwc4GT\/tYx\/3yMnP8QHUZPoHh3WljcB2A4H1U\/MOOent659SRxkcMUMbSSKFVR6cEksBznjq\nfoQRk4yYrO6SS4eO3wTu4GSMncRkgHnjd055PJIOeGvgYVVLVuVoxfu9OaXdtfjs1q2nfnrUacou\nKdmktk0muae7aWvVa230tzH2r8Mta+3XiQMD5aNGoZeRt3Hoec5xyD149cn9OPhsukTaXHAWCt5a\nMfm5IBfnjnkAdTj5eoLEV+WnwPjC3NqLuMRK\/lfP3J8wAn5h246+o6Hk\/qJ4N0wRWcEtrhomCK0u\nQMKSxxwTySM\/XPOGc18XPJaSqVXDWfPNxT0XNzz6t6bJ\/erO0m+fBYaLc1HV81rdb3kn0s+yt1T6\nx195tdJsLWH7TCwYkDI5ORlvm7+o6\/mSWrUh0+61JlR
05-22 00:30:58.804: I/dalvikvm(7530): Jit: resizing JitTable from 8192 to 16384
05-22 00:30:59.134: D/bytesArray(7530): [B#423fc2e0
I think problem is in storing data in file. and also you dont give file extension in server side so it create garbage file. check it and give .jpg or .png with file name.. i hope this will help you..
Though the reply is late but it might help someone..
You are encoding the image in android to base64 before uploading which is right
but u failed to decode it at php side before saving it as image..
<?php
$image = base64_decode($_POST['image']);// decoding the uploaded image
$user = $_POST['user'];
$image_name = $_POST['imageName'];
$file = null;
$filePath = "photos/" . $user;
Hope it helps..

& converted into & when $_POST request is called?

We are working on an application which has 2 modules.
Android Application.
PHP Application
PHP backend application runs on an Apache Server with Centos Server.
Android application basically clicks images, send to the server along with gps coordinates etc form information.
Now the problem arises when the image file is created on the server. When android app calls the url the '&' character is replaced by & amp;, sometimes even by & amp;& amp; and this problem repeats in some of the cases. Once this conversion thing happens, image file is not created properly.
How it can be resolved?
Same code was working alright from past year, this problem begin to arise from last month only....
Following is the code for saving the images at server end :
foreach($_POST as $key => $value) {
$_POST[$x] = $value;
}
$base=$_REQUEST['image'];
$nm=$_REQUEST['name'];
$binary=base64_decode($base);
if(file_exists("uploaded_images/".$nm.".jpg")) {
unlink("uploaded_images/".$nm.".jpg");
}
header('Content-Type: bitmap; charset=utf-8');
$str="uploaded_images/".$nm.".jpg";
$file = fopen($str, 'wb');
fwrite($file, $binary);
fclose($file);
chmod($file,0777);
$ok=1;
echo $ok;
Following is the error log which is encountered if image is not properly saved.
PHP Notice: Undefined index: name in /var/www/html/cbd/def/filesubmitnew.php
Note : filesubmitnew.php is the file name of the above code.
In Android Application for this is how the url is called:
To Create image:
if(buttontext.equals("Img1")) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
v.setImageBitmap(bitmap);
buttontext="";
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, stream);
byte [] byte_arr = stream.toByteArray();
String str1 = Base64.encodeBytes(byte_arr);
System.out.println(""+str1);
if(feuser.equals("offline_access")){
System.out.println("++==--SD CARD");
File externalStorage = Environment.getExternalStorageDirectory();
File folder = new File(externalStorage.getAbsolutePath() +mainFolder + caseId);
if (!folder.exists()) {
folder.mkdir();
}
File pictureFile = new File(externalStorage.getAbsolutePath()+mainFolder+caseId, "1.jpg");
System.out.println(pictureFile);
pictureFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(pictureFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(str1);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+pictureFile,Toast.LENGTH_SHORT).show();
}
else {
Intent i = new Intent ("com.keyboardlabs.newbankge.CameraUploadService");
try {
i.putExtra("imageparams", str1);
i.putExtra("ref_id", caseId);
i.putExtra("imageId", "1");
i.putExtra("CaseType",caseType);
}
catch (Exception e) {
e.printStackTrace();
}
getApplicationContext().startService(i);
}
Following is the camerauploadservice
protected void onHandleIntent(Intent arg0) {
String imageDataBase64encoded = arg0.getStringExtra("imageparams");
String caseID = arg0.getStringExtra("ref_id");
String imageId = arg0.getStringExtra("imageId");
String caseType =arg0.getStringExtra("CaseType");
System.out.println("image_ref="+caseID+"iamgeID="+imageId+"caseType="+caseType+" URL="+URL);
callWebService(imageDataBase64encoded,caseID,imageId,caseType);
}
public void callWebService(String imageData,String refId,String imageId,String caseType){
HttpClient httpclient = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",imageData));
nameValuePairs.add(new BasicNameValuePair("ref_id",refId));
nameValuePairs.add(new BasicNameValuePair("imageId",imageId));
nameValuePairs.add(new BasicNameValuePair("CaseType",caseType));
try{
httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
System.out.println( "Response= " + the_string_response);
}catch(Exception e){
System.out.println( "0" + e.getMessage());
System.out.println("Error in http connection "+e.toString());
}
httpclient.getConnectionManager().shutdown();
}

php for receiving image and text from MultipartEntity

I'm trying to upload an image and some text via MultipartEntity.
I can upload and receive the image, but when I try to add a Stringbody I cannot seem to receive it.
Here's my android code
imports ETC...
public void oncreate(){
.....
nameValuePairs.add(new BasicNameValuePair("image", exsistingFileName));
nameValuePairs.add(new BasicNameValuePair("title", "title"));
}
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
System.out.println("post - if");
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart( nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
System.out.println("post - else");
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
System.out.println("post - done" + entity);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
And my php:
<?php
$uploads_dir = 'uploads/';
$uploadname = $_FILES["image"]["name"];
$uploadtitle = $_FILES["title"]["title"];
move_uploaded_file($_FILES['image']['tmp_name'], $uploads_dir.$uploadname);
file_put_contents($uploads_dir.'juhl.txt', print_r($uploadtitle, true));
?>
I've been around the other questions about MultipartEntity, but cannot seem to find the answer. I've tried sending just the Stringbody, but didn't have any succs in that either. I think the problem is serverside (in the PHP) but any suggestions are welcome.
This is my first question in here - feel free to comment on form and clarity :-)
try this way ,
ByteArrayBody bab1 = bab11;
HttpClient httpClient = new DefaultHttpClient();
httpPost = new HttpPost("link.php?api_name=api");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// this is for String
try {
reqEntity.addPart("udid", new StringBody(UDID));
}
catch (Exception e)
{
}
// this is for image upload
try
{
reqEntity.addPart("file1", bab1);
} catch (Exception e)
{
}
// this is for video upload
try {
if (stPath1 != null) {
Log.e("path 1", stPath1);
Log.v("stDocType1", "video");
File file = new File(stPath1);
FileBody bin = new FileBody(file);
reqEntity.addPart("file1", bin);
}
} catch (Exception e) {
}
httpPost.setEntity(reqEntity);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
The problem was i the php.
When you receive Stringbody there is only one parametre(as opposed to filebody). So I removed the second parametre in $uploadtitle = $_FILES["title"]["title"]; and it worked
<?php
$uploads_dir = 'uploads/';
$uploadname = $_FILES["image"]["name"];
$uploadtitle = $_FILES["title"];
move_uploaded_file($_FILES['image']['tmp_name'], $uploads_dir.$uploadname);
file_put_contents($uploads_dir.'juhl.txt', print_r($uploadtitle, true));
?>
I hope this helps if you have the same problem.

Categories