【问题标题】:uploading image to server php-my-sql(android)将图像上传到服务器 php-my-sql(android)
【发布时间】:2015-03-20 06:24:22
【问题描述】:

我想将我的图像保存到 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);
      }
     }

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

          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 解析器类是

        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的String 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

【问题讨论】:

  • 帮帮我朋友...我需要你的帮助
  • json.toString() 的值是多少?
  • JSONObject json! json 为空。
  • 那么解决方案是什么......当我为任何其他值做......就像 varchar 它是正确的......但是当我为 blob 字段做它是错误的
  • 您的 php 代码似乎发送了错误的响应尝试先打印 json 响应。在 json=sb.toString() 之后;并发布您的问题

标签: php android android-imageview android-json android-internet


【解决方案1】:

正如@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_escape_string() 之前需要 MySQL 连接,否则会生成 E_WARNING 级别的错误,并返回 FALSE。如果未定义 link_identifier,则使用最后一个 MySQL 连接。

【讨论】:

  • Hey Daniel Not 给出的错误类似于 03-20 03:36:15.335: D/JSON Parser(2918): Warning: mysql_real_escape_string(): Access denied for user ' xmveznfp'@'localhost'(使用密码:NO)在 /home/xmveznfp/public_html/big/add_image.php8
  • 你知道如何配置mysql_real_escape_string
猜你喜欢
  • 2011-02-02
  • 2015-03-29
  • 2011-10-15
  • 2016-03-29
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
相关资源
最近更新 更多