将多张图片从 android 保存到 mysql php,但只插入一张图片

Save multiple image into mysql php from android but only one image get inserted

我在 Activity A 中有三个列表视图,如下所示

点击提交button后,文字和图片路径将保存到MySQLimage将保存到PhotoUpload文件夹。

我可以将 3 个文本存储到 MySQL 中,但问题是图像只有一个路径被保存到 MySQL 中。介于两者之间,图像应该保存在 PhotoUpload 中,但它只是保存在文件夹之外!

真令人沮丧!

Activity一个

  public void uploadImageAndText(ArrayList<ImageAndText> listItems, final String id) { // Assume id holds value 2 (ts_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]);
                    Uri uploadImage = i.getImage();
                    Log.e("Image",uploadImage+"");
                    object.put("image", uploadImage.toString());
                    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) {

                for (int index = 0; index < jsonArray.length(); index++) {
                    try {
                        JSONObject jsonObject = jsonArray.getJSONObject(index);
                        String strUri = jsonObject.getString("image");
                        HashMap<String, String> data = new HashMap<String, String>();
                        data.put("listItems", jsonArray.toString());
                        data.put(Configs.KEY_IMAGE, getStringImage(Uri.parse(strUri)));
                        Log.e("AAA",jsonArray.toString());
                        Log.e("String",getStringImage(Uri.parse(strUri)));
                        RequestHandler rh = new RequestHandler();
                        String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data);
                        return result;
                    } catch (Exception e) {
                    }
                }
                return "";
            }

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


        public String getStringImage(Uri imgUri) {

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
                String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
                return encodedImage;
            } catch (Exception e) {
            }

            return "";
        }
    }

staffBenefit.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";

            $image = $_POST['image'];

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

            $sql="SELECT id FROM staff_benefit ORDER BY id ASC";

            $id=1;

            $res=$mysqli->query( $sql );
            while( $rs=$res->fetch_object() ) $id=$rs->id;

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

            $sql="INSERT INTO `staff_benefit` ( `type`, `amount`, `description`, `image`, `ts_id` ) VALUES ( ?, ?, ?, ?, ? )";
            $stmt=$mysqli->prepare( $sql );

            $pathelements=array( realpath( $_SERVER['DOCUMENT_ROOT'] ), 'CRUD', 'PhotoUpload', '' );
            $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;
                } 
            }
            $mysqli->close();
        }
    }
?>

输出

我查看了图片路径,三个是一样的!而且只保存了一张图片(2.png),而且是在PhotoUpload之外,而不是里面:(

path problem ? java problem ? or php problem ???

已编辑(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";


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

            $sql="SELECT id FROM staff_benefit ORDER BY id ASC";

            $id=1;

            $res=$mysqli->query( $sql );
            while( $rs=$res->fetch_object() ) $id=$rs->id;



            $sql="INSERT INTO `staff_benefit` ( `type`, `amount`, `description`, `image`, `ts_id` ) VALUES ( ?, ?, ?, ?, ? )";
            $stmt=$mysqli->prepare( $sql );

            $pathelements=array( realpath( $_SERVER['DOCUMENT_ROOT'] ), 'CRUD', 'UploadPhoto', '' );
            $savepath = realpath( implode( DIRECTORY_SEPARATOR, $pathelements ) ) . "{$id}.png";

            foreach( $listItems as $item ){ 
            $path=time()."$id.png";
            $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path";
            $bytes=file_put_contents( $savepath, base64_decode( $item['image'] ) );
            if( !$bytes ){
            echo 'Error saving image';  
             }else{
             $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;
    }
} 
            }
            $mysqli->close();
        }

?>

路径

C:\xampp\htdocs\Android\CRUD\UploadPhoto

首先,您要覆盖 doInBackground 循环中的图像数据。

其次 PHP 上传代码不在循环中

JAVA

你应该只有一个循环,当你构建你的 JSON 时,把你需要的一切都放在那里

for (ImageAndText i : listItems) {
    JSONObject object = new JSONObject();
    
    String type = i.getType();
    String[] Type = type.split(":");
    String amount = i.getAmount();
    String[] Amount = amount.split(":");
    String description = i.getDescription();
    String[] Description = description.split(":");
    
    //Image
    String image = i.getImage().toString()
    Uri imageUri = Uri.parse(image);
    
    object.put("amount", Amount[1]);
    object.put("type", Type[1]);
    object.put("description", Description[1]);
    object.put("ts_id", id);
    object.put("image", image);
    object.put(Configs.KEY_IMAGE, getStringImage(imageUri));
    
    jsonArray.put(object);
}

然后将JSON放入你的hashmap中发送

@Override
protected String doInBackground(String... params) {
    try {
        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;
    } catch (Exception e) {
        return "";
    }
}

PHP

php会变,你不需要$image = $_POST['image'];

您将从 json $listItems = json_decode( $_POST['listItems'], true );

中获取图像数据

您可以将上传代码放入循环中,并仅在上传成功时插入

foreach( $listItems as $item ){ 
    $path= microtime()."$id.png";
    $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path";
    $bytes=file_put_contents( $savepath, base64_decode( $item['image'] ) );
    if( !$bytes ){
        echo 'Error saving image';  
    }else{
        $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;
    }
} 

编辑:

完整 PHP 脚本

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        if( !empty( $_POST['listItems'] ) ){
            $listItems = json_decode( $_POST['listItems'], true ); 
            $mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb");
            if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";
            $sql="INSERT INTO `staff_benefit` 
                 ( `type`, `amount`, `description`, `image`, `ts_id` ) 
                  VALUES ( ?, ?, ?, ?, ? )";
            if($stmt=$mysqli->prepare($sql )){
                $url="http://192.168.107.115:80/Android/CRUD/PhotoUpload/";
                foreach( $listItems as $item ){ 
                    $image_name = microtime().".png";
                    $save_path = 'PhotoUpload/'.$image_name;
                    $image_url = $url.$image_name;
                    $bytes=file_put_contents($save_path, base64_decode($item['image']));
                    if( !$bytes ){
                        echo 'Error saving image';  
                    }else{
                        $stmt->bind_param('sssss', 
                        $item['type'], 
                        $item['amount'], 
                        $item['description'], 
                        $image_url, 
                        $item['ts_id'] );
                        if( !$res=$stmt->execute()){ 
                            echo 'Query failed with code: '.$stmt->errno;
                        }
                    }
                } 
            }
            $mysqli->close();
        }
    }
?>