0

i've been trying to save an image coming from an android application into a php server db. here is my code..

android:

public class TestCaseActivity extends Activity {

TextView tv;
String text;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tv  = (TextView)findViewById(R.id.textview);
    text    = "";

    try {
        postData();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void postData() throws JSONException{  
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://uknwhu.site40.net/blitz/mydata2.php");
    JSONObject json = new JSONObject();

    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();

    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

    byte [] ba = bao.toByteArray();
    String ba1 = Base64.encodeBytes(ba);

    try {
        // JSON data:
        json.put("name", "jmaraz");
        json.put("position", "SE");
        json.put("photo", ba1);

        JSONArray postjson=new JSONArray();
        postjson.put(json);

        // Post the data:
        httppost.setHeader("json",json.toString());
        httppost.getParams().setParameter("jsonpost",postjson);

        // Execute HTTP Post Request
        System.out.print(json);
        HttpResponse response = httpclient.execute(httppost);

        // for JSON:
        if(response != null)
        {
            InputStream is = (InputStream) response.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            text = sb.toString();
        }

        tv.setText(text);

    }catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

}

here is my php code:

<?php 
include_once("connection.php");
$json = $_SERVER['HTTP_JSON'];

$data = json_decode($json);
//header('Content-Type: application/json;charset=utf-8');
// all are texts 
$name = $data->name;
$pos = $data->position;
$imageString = $data->photo;
$phoneNo = "123456789"; // for testing
// decoding the string 
$realImage = base64_decode($imageString);

//$description = 
//$latitude = 
//$longitude = 


$path = "images/".$phoneNo.".jpg";
$handle = fopen($path, 'wb');
$numbytes = fwrite($handle, $realImage);
fclose($handle);

$imageName = $path; 

// trimming and removing spaces for identifier
$identifier = trim($name);
$identifier = str_replace(" ","",$identifier);

// inserting into database
$query1 = mysql_query("SELECT * FROM details WHERE identifier ='$identifier'");
$row = mysql_num_rows($query1);

if($row >0){
echo "Similar record found! Please change the name and try agin";

}else{
//$query2 = mysql_query("INSERT INTO details (phoneNo, identifier, name,description,latitude,longitude,imageName)


$query2 = mysql_query("INSERT INTO details (phoneNo, identifier, name,imageName)
VALUES('".$phoneNo."', '".$identifier."','".$name."','".$imageName."')");
echo "Done...!";
}

?>

but i get the "Bad Request" message when running the android application. It works fine for texts. How to save the image? Could anybody please help me?

Thanks...

3
  • 1
    Unrelated to your actual question, but your code has glaring SQL injection vulnerabilities. You should either use mysql_real_escape_string() on the strings, or better yet, use PDO with Parameterized Queries (concatenating your own SQL is a horrible idea!). Commented Feb 20, 2012 at 14:29
  • You are also doing http request in the main thread. Plz read: developer.android.com/resources/articles/… Commented Feb 20, 2012 at 14:32
  • thx for the advice.. im still testing on this. Commented Feb 20, 2012 at 14:35

1 Answer 1

2

Try to use below code

    HttpClient httpClient = new DefaultHttpClient();
     HttpContext localContext = new BasicHttpContext();
     HttpPost httpPost = new HttpPost("serverurl");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
      pairs.add(new BasicNameValuePair("username", name));
        pairs.add(new BasicNameValuePair("RecipientMobileNumber", recepnumber));
        pairs.add(new BasicNameValuePair("SenderMobileNumber", sendernumber));
        pairs.add(new BasicNameValuePair("MessageBody", msg));         
     MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for(int index=0; index < pairs.size(); index++) {
    if(pairs.get(index).getName().equalsIgnoreCase("upload")) {
      ContentBody cbFile = new FileBody(new File pairs.get(index).getValue()), "application/octet-stream");
          entity.addPart(pairs.get(index).getName(), cbFile);                    
     } else {                    
               entity.addPart(pairs.get(index).getName(), new StringBody(pairs.get(index).getValue()));
     }
     }
    httpPost.setEntity(entity);
    HttpResponse response = httpClient.execute(httpPost, localContext);
Sign up to request clarification or add additional context in comments.

4 Comments

Server side try to read the image data as how you read the file upload
i need to send texts, coordinates and images altogether. how can i do it with above method?
tx..but i get errors when declaring "MultipartEntity". do you know how to do this via json? Because im suppose to do this using a json array...
why was this accepted as the answer without using json? I came here because it was suppose to be helpful for json arrays - misleading!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.