Upload/download Image issue android + PHP + Base64 - php

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+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49OmCxzyc\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\/2wBDAAEBAQEBAQE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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+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..

Related

Upload a file from Android to the server via PHP

Can anyone help me to make my code work, i.e. upload a file from Android to the server via PHP? I tried it in many different ways but it won't work. I get HTTP Response 200 but the files aren't uploaded on server.
The PHP script I'm using for upload is:
<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['uploaded_file']['name']);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
?>
I also tried using multipart from Httpmime 4.0 but it wont work.
public void uploadFile(String path)
{
File file = new File(path);
try {
HttpClient client = new DefaultHttpClient();
String postURL = upLoadServerUri;
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded_file", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE Wahaj: ","Code : "+ EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class Helpher extends AsyncTask<String, Void, String> {
Context context;
JSONObject json;
ProgressDialog dialog;
int serverResponseCode = 0;
DataOutputStream dos = null;
FileInputStream fis = null;
BufferedReader br = null;
public Helpher(Context context) {
this.context = context;
}
protected void onPreExecute() {
dialog = ProgressDialog.show(Main2Activity.this, "ProgressDialog", "Wait!");
}
#Override
protected String doInBackground(String... arg0) {
try {
File f = new File(arg0[0]);
URL url = new URL("http://localhost:8888/imageupload.php");
int bytesRead;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
String contentDisposition = "Content-Disposition: form-data; name=\"keyValueForFile\"; filename=\""
+ f.getName() + "\"";
String contentType = "Content-Type: application/octet-stream";
dos = new DataOutputStream(conn.getOutputStream());
fis = new FileInputStream(f);
dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
dos.writeBytes(contentDisposition + NEW_LINE);
dos.writeBytes(contentType + NEW_LINE);
dos.writeBytes(NEW_LINE);
byte[] buffer = new byte[MAX_BUFFER_SIZE];
while ((bytesRead = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
dos.writeBytes(NEW_LINE);
dos.writeBytes(SPACER + BOUNDARY + SPACER);
dos.flush();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
Log.w(TAG,
responseCode + " Error: " + conn.getResponseMessage());
return null;
}
br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
Log.d(TAG, "Sucessfully uploaded " + f.getName());
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
dos.close();
if (fis != null)
fis.close();
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return String.valueOf(serverResponseCode);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
This is the AsyncTask "Helpher" class used for upload image from Android. To call this class use like syntax below.
new Main2Activity.Helpher(this).execute(fileUri.getPath());
Here fileUri.getPath() local image location.

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();
}
}
}

Android image upload not getting to PHP script

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.

Android: How to get image from remote server

I am developing an Android app that should get an image from remote server. Am using WAMP as my server and PHP as programming language. I know how to get text data using JSON.
Am not using blob to store image.
Images have stored in a folder on server. Url of image is stored in db table.
I tried the following snippet, I got this from net but it is not giving any error and also it is not displaying image
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
String base64Image = jsonObj.getString("pprs");
Toast.makeText(getBaseContext(), base64Image, Toast.LENGTH_LONG).show();
byte[] rawImage = Base64.decode(base64Image, Base64.DEFAULT);
bmp = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
}
}
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
if($row = mysql_fetch_assoc($query))
{
$response = $row['imageUrl'];
}
$response = base64_encode($response);
echo '{"pprs":'.json_encode($response).'}';
mysqli_close($con);
?>
I checked my php code with html(with out encoding $response value) am getting image there, but not in Android.
I am not good with Php, but if you return the file url via a JSON reponse you can use the following code for downloading the file.
int count;
try {
URL url = new URL("http://url of your file");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
## Edit ##
After the Image is downloaded you can create a Bitmap from the Image Path/InputStream and assign it to the Image View like this
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
Original source
try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
bitmapPath = jsonObj.getString("pprs");
}
}
try {
Toast.makeText(getBaseContext(), "http://10.0.2.2/sareesProject/"+bitmapPath, Toast.LENGTH_SHORT).show();
URL url = new URL("http://10.0.2.2/sareesProject/"+bitmapPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
bmp = myBitmap;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(bmp == null)
Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
//new HomePage().show("in con");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
//show(line);
//new HomePage().show("in while");
//new HomePage().show("l="+line);
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(, text, duration)
} finally {
try {
if(reader != null)
{
try{reader.close();}
catch(Exception e){e.printStackTrace();}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//end of convertStreamToString
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
$response = array();
while($row = mysql_fetch_assoc($query))
{
$response[] = $row['imageUrl'];
}
echo json_encode($response);
mysqli_close($con);
?>
//--------------------
Fnally i got it.............
First of all my server file returns the following
{"pprs":"upload/22.png"}
from this i extracted upload/22.png using JSON
Now bitmapPath contains upload/22.png
Thank you very much to insomniac giving suggestions.............
If it is helpful to any one vote for me..............

Runtime exception while uploading image to the server

The below is the runtime exeception which i got while am trying to upload a image to the server.
And am trying to upload a image using my local server(WAMP) and my android code is
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/Sunset.jpg");
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.background1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.49/android/upload_image.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(uploadimage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(uploadimage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("Error http connection"+e.toString());
}
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(uploadimage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting string buffer to string
Toast.makeText(uploadimage.this, "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}
and this is my php code which i got from internet .
<?php
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete!!, Please check your php file directory……';
?>
Can any one help me in this to solve my problem. thanks in advance
You have to create one additional directory in c:\ then provide read, write and execute permission on it.
In your php code please write the absolute path of the storage location.
This may solve your problem.
Remember to run the IIS server in Administrator mode.
Inetpub is created by the SYSTEM user. This means that you aren't allowed to make modifications to it, or any of its subdirectories, without admin permissions. Try changing the permissions of the inetpub folder so anyone can modify the files. Right-click -> Properties -> ... I forget what to do after that. (I'm in Linux right now). If that doesn't work, make sure you are running IIS as an Administrator.

Categories