java – Sending a file to PHP-ThrowExceptions

Exception or error:

In my Android Studio code, I open up my camera and take a picture which I can save. However, I then want to send this JPG picture to my PHP code. I have it sorted for sending strings to PHP however when I try to send an image it doesn’t work. Because of this I have encoded my image into a base64 string to try and send it that way but it’s still not working.

Java code:

public class celebs extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        //Toast.makeText(getBaseContext(),s,Toast.LENGTH_SHORT).show();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @SuppressLint("WrongThread")
    @Override
    protected String doInBackground(String... params) {

        sharedPreferenceConfig = new SharedPreferenceConfig(getApplicationContext());
        Intent intent = getIntent();
        File Image = (File) intent.getSerializableExtra("Image");

        String encode = encodeFileToBase64Binary(Image);

        try {

            String data = URLEncoder.encode("Image", "UTF-8") + "=" +
                    URLEncoder.encode(String.valueOf(Image), "UTF-8");
            //URL url = new URL("http://192.168.43.35:80/App/pythonconnect.php?" + data);
            URL url = new URL("http://10.167.120.26/App/pythonconnect.php?" + encode);
            System.out.println("1");
            URLConnection con = url.openConnection();
            System.out.println("2");
            con.setDoOutput(true);
            System.out.println("3");

            BufferedReader read = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder s = new StringBuilder();
            String line = null;
            while ((line = read.readLine()) != null) {
                s.append(line);
            }
            final String result = s.toString();
            System.out.println(result);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}


@RequiresApi(api = Build.VERSION_CODES.O)
private static String encodeFileToBase64Binary(File file){
    String encodedfile = null;
    try {
        FileInputStream fileInputStreamReader = new FileInputStream(file);
        byte[] bytes = new byte[(int)file.length()];
        fileInputStreamReader.read(bytes);
        encodedfile = Base64.getEncoder().encodeToString(bytes);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return encodedfile;
}

ERROR:

W/System.err: java.io.FileNotFoundException: http://192.168.43.35:80/App/pythonconnect.php?Image=%2F9j%2F4QFnRXhpZgAATU0AKgAAAAgABwEAAAQAAAABAAAPwAEBAAQAAAABAAAL0AEPAAIAAAAHAAAAYgEQAAIAAAAJAAAAaQESAAMAAAABAAMAAAEyAAIAAAAUAAAAcodpAAQAAAABAAAAhgAAAABHb29nbGUAUGl4ZWwgM2EAMjAyMDowMzoxNSAxNjozODoyMwAADYKaAAUAAAABAAABKIKdAAUAAAABAAABMIgnAAMAAAABAEsAAJAQAAIAAAAHAAABOJIBAAoAAAABAAABP5ICAAUAAAABAAABR5IGAAUAAAABAAABT5IJAAMAAAABAAAAAJIKAAUAAAABAAABV5KQAAIAAAAENjY0AKACAAQAAAABAAAPwKADAAQAAAABAAAL0KQMAAMAAAABAAEAAAAAAAAAmCMDO5rKAAAAALQAAABkKzAwOjAwAP%2F%2F%2FWgAAABkAAAAqQAAAGQAAABjAAAD6AAAEVgAAAPo%2F%2BAAEEpGSUYAAQEAAAEAAQAA%2F9sAQwACAQEBAQECAQEBAgICAgIEAwICAgIFBAQDBAYFBgYGBQYGBgcJCAYHCQcGBggLCAkKCgoKCgYICwwLCgwJCgoK%2F9sAQwECAgICAgIFAwMFCgcGBwoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoK%2F%2BICZElDQ19QUk9GSUxFAAEBAAACVAAAAAAEAAAAbW50clJHQiBYWVogB%2BAADAAIAAkAJgAcYWNzcAAAAAAAAAAAR09PRwAAAAAAAAAAAAAAAAAAAAAAAPbWAAEAAAAA0y1HT09HdeGmsTw0N2MQyKtmBjKiigAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALZGVzYwAAAQgAAABAY3BydAAAAUgAAABad3RwdAAAAaQAAAAUYmtwdAAAAbgAAAAUclhZWgAAAcwAAAAUZ1hZWgAAAeAAAAAUYlhZWgAAAfQAAAAUclRSQw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p0wfpVld0w3ISQB19qlRsBVVXjlVUyN6fNkDgU6dp4UjhNw5NudqxDt3%2FH%2BtNkvbaeVo4ZQzRHB24x2%2FOnMJEaN4pMSPyXBPGPapMx0kEczI7XDCTIwhb7nA%2FKn3xtYHCW8geVF%2BYYIG4%2Bmaq3Nnbeetzjb8w3Ko4xj26VavVtSEMMZVg4JYvnPt04oAZNFaarMun3kq7wMIAuNxPb3zmrEFtOZR5t2FaOJgdxIJ%2FwDr5%2FyKSXdviME6xZO4lRg4Hv8A4eopggaOQG6uQzkkqNpAxTNCG1M8EACQSMATyF44J5qxLFdWmniRZFd5zvIPHHHH%2FwBYUkokuV2QyFQhG7CggjPP%2BfpU7WqSIGYgHPykihIDJsRb2btLNGqTFyWfcTkEnI5%2Bv6mrl0mJh9hsi5dDlnI9%2FwDPp1qW6s4zEGkUMBy2cEU%2B0kt5FeJSY227UYDOcke2OlZAQ2VxJfCRHYmUITnrz6%2B%2FSobqb7OY3v4gVBO3K53ZpNOt5La8mfljuI%2BY%2FpirbGOaYTXMYO1sqMELn8PxquYhqxJdWZ1Bopbm02KqZDYySCOf0pbxbGKLdESCW6Fun1z71De3E8Ej3M%2F%2BpH3FiXBX%2FPp%2BVS2lk01k1zC6FmYAeZggf5%2Fzmr3EKst8EWJrf92vysVGenr%2BlS4tonLRoFcqTgcH%2FPWnQfbYUf7ZcMTgAc8ADt%2FL8hUFub2GARJJkmT77L2yB6UgHm3tZpEm853cEF
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:255)
        at com.example.wit.Celeb$celebs.doInBackground(Celeb.java:99)
        at com.example.wit.Celeb$celebs.doInBackground(Celeb.java:51)
        at android.os.AsyncTask$3.call(AsyncTask.java:378)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)

My php code:

<?php
    if (isset($_POST["Image"])) {
      "include connection.php";
      $image = $_POST["Image"];

      $message = exec("/Applications/XAMPP/xamppfiles/htdocs/App/database.py 2>&1 '$imagestr'");
      echo($message);
    }
?>
How to solve:

Sending image as base64 encoded string in not an ideal method because GET and POST have character limitation in their request. This will cause 413 request entity too large error.

Best method for sending image to server is using Multipart request from Android.

Take a look at this solution

Leave a Reply

Your email address will not be published. Required fields are marked *