【问题标题】:Get trouble when want to store image path into MySQL想将图像路径存储到 MySQL 时遇到麻烦
【发布时间】:2016-04-15 12:13:28
【问题描述】:

在我的 Activity A 中,它有一个 listView,其中图像和文本是从 Activity B 获取的。

Activtiy 一个带有图片和文字的列表视图

点击保存按钮后,我想通过php将图片路径和文字存入mysql,图片会保存在目录中。

活动 A

  public void uploadImageAndText(ArrayList<ImageAndText> listItems, final String id) {
            JSONArray jsonArray = new JSONArray();
            try {
                for (ImageAndText i : listItems) {
                    JSONObject object = new JSONObject();
                    String type = i.getType();
                    String[] Type = type.split(":");
                    object.put("type", Type[1]);
                    Toast.makeText(getApplicationContext(), Type[1], Toast.LENGTH_LONG).show();
                    String amount = i.getAmount();
                    String[] Amount = amount.split(":");
                    object.put("amount", Amount[1]);
                    String description = i.getDescription();
                    String[] Description = description.split(":");
                    object.put("description", Description[1]);
                    Bitmap uploadImage = i.getImage();
                    String image = getStringImage(uploadImage);
                    object.put("image", image);
                    object.put("ts_id", id);
                    jsonArray.put(object);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            AddStaff ru = new AddStaff(jsonArray);
            ru.execute();

        }

        class AddStaff extends AsyncTask<String, Void, String> {
            ProgressDialog loading;

            JSONArray jsonArray;

            AddStaff(JSONArray jsonArray) {
                this.jsonArray = jsonArray;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(AddClaims.this, "Please Wait", null, true, true);
            }

            @Override
            protected String doInBackground(String... params) {
                HashMap<String, String> data = new HashMap<String, String>();
                data.put("listItems", jsonArray.toString());
                RequestHandler rh = new RequestHandler();
                String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data);
                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
            }
        }


        public String getStringImage(Bitmap bmp) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
            return encodedImage;
        }
    }

php

  <?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        if( !empty( $_POST['listItems'] ) ){

            $mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb");
            if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";/* try not to reveal too much info! */

            /* The example you followed had this line! */
            $image = $_POST['image'];

            $listItems = json_decode( $_POST['listItems'], true ); 

            /* This never gets called - should it? */
            $sql="SELECT id FROM staff_benefit ORDER BY id ASC";
            /*
                This fetches ALL ids from the staff_benefit table
                so which ID do you need? Iterating through the 
                recordset will effectively return the last one!
            */

            $id=0;



            /*
                I assume that $id is supposed to get 
                the value from th above sql query???
            */      
            $res=$mysqli->query( $sql );
            while( $rs=$res->fetch_object() ) $id=$rs->id;

            $path="$id.png";
            $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path";


            /* Use only placeholders in your prepared statement */
            $sql="INSERT INTO `staff_benefit` ( `type`, `amount`, `description`, `image`, `ts_id` ) VALUES ( ?, ?, ?, ?, ? )";
            $stmt=$mysqli->prepare( $sql );


            /* Save the image to disk: I prefer to use the actual path for storing files */
            $pathelements=array( realpath( $_SERVER['DOCUMENT_ROOT'] ), 'CRUD', 'PhotoUpload', '' );/* empty entry adds trailing slash to path */
            $savepath = realpath( implode( DIRECTORY_SEPARATOR, $pathelements ) ) . "{$id}.png";

            $bytes=file_put_contents( $savepath, base64_decode( $image ) );
            if( !$bytes ){
                echo 'Error saving image';  
            }

            if ( $stmt && $bytes ) {
                 foreach( $listItems as $item ){ 

                    $stmt->bind_param('sssss', $item['type'], $item['amount'], $item['description'], $actualpath, $item['ts_id'] );
                    $res=$stmt->execute();

                    if( !$res ) echo 'Query failed with code: '.$stmt->errno;/* Again, not too much info */
                } 
            }
            $mysqli->close();
        }
    }
?>

单击目录中的图片时,无法显示图片,因为文件是 空的

【问题讨论】:

  • 这个错误出现在php或java中?
  • 在 sql 中,您使用 file_put_contents() 作为图像 - 这将返回写入的字节数而不是路径。另外,$image 的函数调用来自哪里?
  • @DurimJusaj php..no logcat 错误
  • @RamRaider 正确的方法是什么?插入时,我使用String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
  • sql 语句$sql="SELECT id FROM staff_benefit ORDER BY id ASC"; 没有被执行——这是实际代码还是从中提取的?您分配 $id=0; 然后在 $path 变量中使用 $id - 这将始终相同 ~ uploads/0.png

标签: php android mysql image path


【解决方案1】:
<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        if( !empty( $_POST['listItems'] ) ){

            $mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb");
            if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";/* try not to reveal too much info! */

            /* The example you followed had this line! */
            $image = $_POST['image'];

            $listItems = json_decode( $_POST['listItems'], true ); 

            /* This never gets called - should it? */
            $sql="SELECT id FROM staff_benefit ORDER BY id ASC";
            /*
                This fetches ALL ids from the staff_benefit table
                so which ID do you need? Iterating through the 
                recordset will effectively return the last one!
            */

            $id=0;



            /*
                I assume that $id is supposed to get 
                the value from th above sql query???
            */      
            $res=$mysqli->query( $sql );
            while( $rs=$res->fetch_object() ) $id=$rs->id;

            $path="$id.png";
            $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path";


            /* Use only placeholders in your prepared statement */
            $sql="INSERT INTO `staff_benefit` ( `type`, `amount`, `description`, `image`, `ts_id` ) VALUES ( ?, ?, ?, ?, ? )";
            $stmt=$mysqli->prepare( $sql );


            /* Save the image to disk: I prefer to use the actual path for storing files */
            $pathelements=array( realpath( $_SERVER['DOCUMENT_ROOT'] ), 'CRUD', 'PhotoUpload', '' );/* empty entry adds trailing slash to path */
            $savepath = realpath( implode( DIRECTORY_SEPARATOR, $pathelements ) ) . "{$id}.png";

            $bytes=file_put_contents( $savepath, base64_decode( $image ) );
            if( !$bytes ){
                echo 'Error saving image';  
            }

            if ( $stmt && $bytes ) {
                 foreach( $listItems as $item ){ 

                    $stmt->bind_param('sssss', $item['type'], $item['amount'], $item['description'], $actualpath, $item['ts_id'] );
                    $res=$stmt->execute();

                    if( !$res ) echo 'Query failed with code: '.$stmt->errno;/* Again, not too much info */
                } 
            }
            $mysqli->close();
        }
    }
?>

【讨论】:

  • 嗨,我可以在这里问你吗?为什么我在 PhotoUpload 文件夹中点击图片时,它说文件是空的?
  • $_POST['image']的内容是什么?在尝试调试这样的事情时,打印出 $_POST 变量以查看您拥有哪些字段以及哪些值总是有用的!
  • 我在$image = $_POST['image']; 中得到未定义的索引。我不知道如何解决这个问题。如您所见,我想将带有文本和图像的listView 发送到MySQL,但我什至找不到将arrayList 发送到MySQL 的教程。我按照上面的教程进行操作,但没有使用 arraylist
  • 好的 - 未定义的索引意味着 POST 数据中没有 image 字段 - 您遵循的示例有 $_POST['mage'] 引用。将echo '&lt;pre&gt;',print_r($_POST,true),'&lt;/pre&gt;'; 添加到您的 php 中,看看您在 php 中究竟做了什么
  • 我看到很多字母
猜你喜欢
  • 1970-01-01
  • 2020-11-02
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 2015-03-26
  • 2018-10-22
  • 2020-06-15
  • 1970-01-01
相关资源
最近更新 更多