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



我想把我的图像保存到php我的sql数据库。。。我在添加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);
      }
     }

我正在将图像字符串值传递给异步任务活动

          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 Parser类是

        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$3.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$1.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$2.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仍然为空。

因此,在得到异常之前,在那里添加日志以查看响应:

 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) {
   ............

注:使用MySQL_real_eescape_string()之前需要MySQL连接,否则会生成E_WARNING级别的错误,并返回FALSE。如果没有定义link_identifier,则使用最后一个MySQL连接。

最新更新