php - 想要将图像路径存储到 MySQL 时遇到麻烦

标签 php android mysql image path

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

Activtiy 带有图像和文本的 ListView

enter image description here

当点击保存按钮时,我想通过php将图片路径和文本存入mysql,图片将存储在目录中。

Activity 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();
        }
    }
?>

When click image in directory, can't display image because the file is empty

enter image description here

最佳答案

<?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 - 想要将图像路径存储到 MySQL 时遇到麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34717255/

相关文章:

java - 来自 Java 和 Php 的 https 链接的不同输出

mysql - 如何在 Debian 10 上的 Mysql 8.0 中启用远程连接

php - 允许访问 www/html 文件夹之外的文件

android - 如何在 Android 中为 "command line"C 程序设置互联网权限?

java - Android:在应用程序生命周期中仅初始化一次套接字

android - 通过 Android 共享时 Google+ 应用程序显示错误的图片

MySql:将 BLOB 转储到本地文件中

mysql - 每 5 个字符分割一个字符串并获得不同的字符串

php - 获取 "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version"

php - 评级算法似乎关闭