2012-02-20 53 views
0

我一直在試圖將來自android應用程序的圖像保存到php服務器數據庫中。 這裏是我的代碼..如何通過json數組將圖像保存在mysql數據庫中?

安卓

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 
    } 
} 

}

這裏是我的PHP代碼:

<?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...!"; 
} 

?> 

但在運行時,我得到了 「錯誤的請求」 消息android應用程序。它適用於文本。如何保存圖像?有誰能幫我嗎?

謝謝...

+1

無關你的實際問題,但你的代碼有明顯的SQL注入漏洞。你應該在字符串上使用'mysql_real_escape_string()',或者更好的方法是使用帶參數化查詢的PDO(連接你自己的SQL是一個可怕的想法!)。 – Kitsune 2012-02-20 14:29:09

+0

您也在主線程中執行http請求。 PLZ閱讀:http://developer.android.com/resources/articles/painless-threading.html – Macarse 2012-02-20 14:32:01

+0

thx的意見..即時通訊仍在測試這一點。 – Manoj 2012-02-20 14:35:05

回答

2

嘗試使用下面的代碼

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); 
+1

服務器端嘗試讀取圖像數據以讀取文件上傳 – Vamshi 2012-02-20 14:36:25

+0

我需要發送文本,座標和圖像。我如何用上述方法做到這一點? – Manoj 2012-02-20 14:54:34

+1

我編輯了我的答案,將值添加到像上面這樣的對列表中...... – Vamshi 2012-02-20 14:57:11

相關問題