0

I convert my image to BITMAP and then i convert it to String (from byte[] array). I then send it as POST REQUEST to my .php page of the server and i expect it to upload it in my database as LONGBLOB type.

JAVA CODE

@Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_CANCELED){
            return;
        }       //IF USER CANCELED, EXIT

        if(requestCode == CAMERA_CODE){
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            this.profile_image.setImageBitmap(bitmap);
            uploadImageToDB(bitmap);

        }else if(requestCode == GALLERY_CODE){
            if(data != null){
                Uri contentUri = data.getData();
                try{
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), contentUri);
                    this.profile_image.setImageBitmap(bitmap);
                    uploadImageToDB(bitmap);

                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        }

    }

    private byte[] convertBitmapToLongblob(Bitmap bitmap){
        if(bitmap != null) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
            return stream.toByteArray();
        }

        return null;
    }

    private String convertLongblobToString(byte[] longblob){
        if(longblob != null){
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            String encoded = android.util.Base64.encodeToString(longblob, Base64.DEFAULT);
            return encoded;
        }

        return null;
    }

    private void uploadImageToDB(Bitmap imageBitmap){
        final String uploadImageUrl = "http://192.168.1.8/myServer/uploadImage.php";
        final String binaryImage = convertLongblobToString(convertBitmapToLongblob(imageBitmap));
        final int userId = this.sp.getInt("id", -1);   //sp -> SharedPreferences with user's info

        if(userId != -1 && binaryImage != null){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL url = new URL(uploadImageUrl);
                        URLConnection conn = url.openConnection();
                        if (!(conn instanceof HttpURLConnection)) {
                            throw new IOException("Not on HTTP Connection");
                        }
                        HttpURLConnection httpConn = (HttpURLConnection) conn;
                        httpConn.setConnectTimeout(15000);
                        httpConn.setReadTimeout(10000);
                        httpConn.setRequestMethod("POST");
                        httpConn.setDoOutput(true);
                        httpConn.setDoInput(true);

                        Uri.Builder builder = new Uri.Builder()
                                .appendQueryParameter("user_id", userId + "")
                                .appendQueryParameter("binary_image", binaryImage)
                                ;
                        String queryPar = builder.build().getEncodedQuery();

                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(httpConn.getOutputStream(), StandardCharsets.UTF_8));
                        bw.write(queryPar);
                        bw.flush();
                        bw.close();
                        httpConn.connect();

                        int response = httpConn.getResponseCode();
                        if (response == HttpURLConnection.HTTP_OK) {
                            InputStream in = httpConn.getInputStream();
                            BufferedReader br = new BufferedReader(new InputStreamReader(in));
                            String data = "";
                            String temp;
                            while ((temp = br.readLine()) != null) {
                                data += temp + "\n";
                            }
                            br.close();
                            in.close();
                            JSONObject jsob = new JSONObject(data);
                            String res = jsob.getString("response");
                            switch (res) {
                                case "SUCCESS":
                                    System.out.println("success");
                                    break;
                                case "FAILED":
                                    System.out.println("failed");
                                    break;
                            }
                        }

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
            thread.start();
            try {
                thread.join();
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }

So, then i take my $_POST attribute of this string (byte[] array) converted image and i want it to be saved in my MYSQL database so i can retrieve it later. I have tried so many things but nothing works for me... It keeps saving a [BOB 1B] which i guess is wrong, because it's size shouldn't be 1 byte.

PHP CODE

<?php
    if($_SERVER['REQUEST_METHOD'] == "POST"){
        require "./connection.php";
        uploadImageToDB();
    }


    function uploadImageToDB(){
        global $conn;

        $userId = intval($_POST['user_id']);
        $binImageStr = $_POST['binary_image'];

        $binaryImage = unpack("C*",$binImageStr);
        //AVOID SQL INJECTIONS BY MAKING A SECURE SQL COMMAND
        $sql = sprintf("UPDATE extra_user_info SET profile_image = %0b WHERE user_id = %d;",
                    ((binary)$binImageStr),
                    mysqli_real_escape_string($conn, $userId)
                );

        $result = mysqli_query($conn, $sql);
        if($result){            
            echo json_encode(
                [
                    "response"=>"SUCCESS"
                ]
            );     //CASE 1 (SUCCESS)
        }else{
            echo json_encode(
                [
                    "response"=>"FAILED"
                ]
            );      //CASE 2 (FAILURE)
        }

        mysqli_close($conn);
    }
?>
  • 1
    Please don't write in all caps. Not only is that considered yelling, it also makes the text harder to read. – M. Eriksson Feb 27 '22 at 10:01
  • oh... sorry, im not yelling. It was my way to split my text and my code. I see it was wrong. I apoligize. – D0rkDevelop4r Feb 27 '22 at 10:03
  • There's an [edit] button under your question that you can click on to correct it. – Robert Longson Feb 27 '22 at 10:05
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Feb 27 '22 at 10:43
  • Thanks a lot. I thought **mysqli_real_escape_string()** gives you this security against SQL Injections but apparently it doesn't. – D0rkDevelop4r Feb 27 '22 at 11:14

0 Answers0