Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何通过json数组在mysql数据库中保存图像?_Android_Json_Image - Fatal编程技术网

Android 如何通过json数组在mysql数据库中保存图像?

Android 如何通过json数组在mysql数据库中保存图像?,android,json,image,Android,Json,Image,我一直在尝试将来自android应用程序的图像保存到php服务器数据库中。 这是我的密码 安卓: public class TestCaseActivity extends Activity { TextView tv; String text; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.lay

我一直在尝试将来自android应用程序的图像保存到php服务器数据库中。 这是我的密码

安卓:

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

?>

尝试使用下面的代码

    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);
HttpClient-HttpClient=newdefaulthttpclient();
HttpContext localContext=新的BasicHttpContext();
HttpPost HttpPost=新的HttpPost(“服务器URL”);
列表对=新的ArrayList();
添加(新的BasicNameValuePair(“用户名”,名称));
添加(新的BasicNameValuePair(“RecipientMobileNumber”,recepnumber));
添加(新的BasicNameValuePair(“SenderMobileNumber”,sendernumber));
添加(新的BasicNameValuePair(“MessageBody”,msg));
MultipartEntity=新的MultipartEntity(HttpMultipartMode.BROWSER_兼容);
对于(int index=0;index
与您的实际问题无关,但您的代码存在明显的SQL注入漏洞。您应该在字符串上使用
mysql\u real\u escape\u string()
,或者更好地使用参数化查询的PDO(连接您自己的SQL是一个可怕的想法!)。您还可以在主线程中执行http请求。请看:谢谢你的建议。。我还在测试这个。服务器端尝试读取图像数据,就像你读取上传的文件一样。我需要发送文本、坐标和图像。我怎样才能用上面的方法来做呢?tx..但是我在声明“MultipartEntity”时会出错。您知道如何通过json实现这一点吗?因为我想用一个json数组来做这件事……为什么不使用json就接受这个答案呢?我之所以来到这里,是因为它被认为对json数组很有帮助——误导!