上传图片到服务器 php-my-sql(android)

uploading image to server php-my-sql(android)

我想将我的图像保存到 php-my-sql 数据库... 我在 add-img 字段中有一张图片检查我的代码

     protected void onActivityResult(int requestCode, int resultCode, Intent  data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        InputStream inputStream;
        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {

          Bitmap bmp = (Bitmap) data.getExtras().get("data");
            add_img.setImageBitmap(bmp);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 90, stream);
            byte[] byte_arr = stream.toByteArray();
            imageString = Base64.encodeBytes(byte_arr);
      }
     }

我正在将图像字符串值传递给 asynktask activity

          protected String doInBackground(String... args) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            email_value="gdfgdfgd";
            params.add(new BasicNameValuePair("email_id",email_value));
            params.add(new BasicNameValuePair("image",imageString));
            JSONObject json = jsonParser.makeHttpRequest(url_create_image,
                    "POST", params);
            Log.d("Create Response", json.toString());
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

我的 Json 解析器 Class 是

        public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 
        try {
            if(method.equals("POST")){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equals("GET")){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 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 {
        jObj = new JSONObject(json);

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }}

我的 php 的字符串 url 是

<?php

$response = array();
if (isset($_POST['email_id'])) 
 {   
 $base= $_POST['image'];
  $buffer = base64_decode($base);
  $buffer = mysql_real_escape_string($buffer);
  $email = $_POST['email_id'];

  require_once __DIR__ . '/db_connect.php';
  $db = new DB_CONNECT();
  $result = mysql_query("INSERT INTO image_table(email,image)   VALUES('$email ','$buffer')");
  if ($result) {
    $response["success"] = 1;
    $response["message"] = "Image successfully Added.";
    echo json_encode($response);
   } else {
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";
    echo json_encode($response);
  }
 } else {
  $response["success"] = 0;
  $response["message"] = "Required field(s) is missing";
  echo json_encode($response);
}
 ?>      

我遇到了这样的错误

 03-20 02:08:38.276: E/JSON Parser(2574): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-20 02:08:38.286: E/AndroidRuntime(2574): FATAL EXCEPTION: AsyncTask #1
03-20 02:08:38.286: E/AndroidRuntime(2574): Process: com.big_property, PID: 2574
03-20 02:08:38.286: E/AndroidRuntime(2574): java.lang.RuntimeException: An error occured while executing doInBackground()
03-20 02:08:38.286: E/AndroidRuntime(2574):     at android.os.AsyncTask.done(AsyncTask.java:300)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at java.lang.Thread.run(Thread.java:841)
03-20 02:08:38.286: E/AndroidRuntime(2574): Caused by: java.lang.NullPointerException
03-20 02:08:38.286: E/AndroidRuntime(2574):     at com.big_property.Post_Property_Activity3$CreateNewFloor.doInBackground(Post_Property_Activity3.java:378)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at com.big_property.Post_Property_Activity3$CreateNewFloor.doInBackground(Post_Property_Activity3.java:1)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at android.os.AsyncTask.call(AsyncTask.java:288)
03-20 02:08:38.286: E/AndroidRuntime(2574):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-20 02:08:38.286: E/AndroidRuntime(2574):     ... 4 more

正如@Harry 指出的那样,PHP 代码确实没有发送可以解析为 JSONObject.

的响应

此日志条目:

E/JSON Parser(2574): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

表示这里出现异常:

 try {
    jObj = new JSONObject(json);

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

...因此 jObj 结果仍然为 null。

因此,在出现异常之前添加日志记录以查看响应是什么:

 try {
    Log.d("JSON Parser", "json response: " + json);
    jObj = new JSONObject(json); //Throwing an exception

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

要防止 NullPointerException,请更改此代码:

     //Check if not null before referencing json object to prevent NPE
     if (json != null){   
       Log.d("Create Response", json.toString());
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

            } else {
                // failed to create product
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
      }
      else{
         Log.e("doInBackground", "json is null");
      }

编辑:查看日志并进行一些研究后,您似乎需要 MySQL 连接才能使用 mysql_real_escape_string()

在您的 PHP 中试试这个:

<?php

$response = array();
if (isset($_POST['email_id'])) 
 {   
 $base= $_POST['image'];
  $buffer = base64_decode($base);
  $email = $_POST['email_id'];

  require_once __DIR__ . '/db_connect.php';
  $db = new DB_CONNECT();
  $query = sprintf("INSERT INTO image_table(email,image)   VALUES('%s','%s')", $email, mysql_real_escape_string($buffer));

  $result = mysql_query($query);
  if ($result) {
   ............

Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.