3

everyone. I am stuck on this project I am working on. I want to be able to upload an image from the android gallery, encode that image to a base64 string and send to PHP web service, as a get variable, then decode the image from the other end and do with it as I wish.

So far I am able to select the image, from the gallery and even encode to base64 string and storing in android preference.

The problem is, I think that not all the string is being sent to the PHP service (Some is truncated).

Why do I think so? My Log.d showed me different strings when dumped at different locations.

The code that gets the image and encodes is:-

private void galleryIntent()
{
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Please select a file"),1);
}

private String onSelectFromGalleryResult (Intent data) {

    if (data != null) {
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver() , data.getData()) ;
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;

        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) ;

        byte[] imageBytes = byteArrayOutputStream.toByteArray() ;

        Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ;

        return Base64.encodeToString (imageBytes, Base64.DEFAULT) ;
    } else {
        return null ;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    SharedPreferences sharedPreferences =  getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit() ;

    if (resultCode == Activity.RESULT_OK) {

        if (requestCode == 1) {
            /*Here we handle the image gotten from the gallery*/
            String encodedGalleryImage = onSelectFromGalleryResult(data);

           editor.putString("userEncodedGalleryImage" , encodedGalleryImage);

        } else if (requestCode == 0) {
            /*Here we handle the image that was take using the camera*/

        }

        editor.apply();
    }
}

Here we call the asynctask class

private void callAsynctask () {
  SharedPreferences sp = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);

    String userQuestionAttachement = sp.getString("userEncodedGalleryImage" , "") ;

Log.d("callingEncodedImage" , userQuestionAttachement) ;
}

The problem I have is that the log from Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ; is different from Log.d("callingEncodedImage" , userQuestionAttachement) ;

There both have same beginning, but different endings. I expect to see the same characters.

Can someone please help me sort it out?

2
  • base64 string sometimes can be too large to be sent in one go. Better option would be to upload image file using multipart. Commented Oct 26, 2016 at 10:49
  • Hello @VivekMishra how will u do that? I Think That is what I need!... Commented Oct 26, 2016 at 12:08

2 Answers 2

2

In Android,

 new UploadFileAsync().execute("");



  private class UploadFileAsync extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        try {
  String sourceFileUri = "/mnt/sdcard/abc.png";

            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            File sourceFile = new File(sourceFileUri);

            if (sourceFile.isFile()) {

                try {
                    String upLoadServerUri = "http://website.com/abc.php?";

                    // open a URL connection to the Servlet
                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);
                    URL url = new URL(upLoadServerUri);

                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true); // Allow Inputs
                    conn.setDoOutput(true); // Allow Outputs
                    conn.setUseCaches(false); // Don't use a Cached Copy
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("ENCTYPE",
                            "multipart/form-data");
                    conn.setRequestProperty("Content-Type",
                            "multipart/form-data;boundary=" + boundary);
                    conn.setRequestProperty("bill", sourceFileUri);

                    dos = new DataOutputStream(conn.getOutputStream());

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
                            + sourceFileUri + "\"" + lineEnd);

                    dos.writeBytes(lineEnd);

                    // create a buffer of maximum size
                    bytesAvailable = fileInputStream.available();

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];

                    // read file and write it into form...
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                    while (bytesRead > 0) {

                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math
                                .min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0,
                                bufferSize);

                    }

                    // send multipart form data necesssary after file
                    // data...
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens
                            + lineEnd);

                    // Responses from the server (code and message)
                    serverResponseCode = conn.getResponseCode();
                    String serverResponseMessage = conn
                            .getResponseMessage();

                    if (serverResponseCode == 200) {

                        // messageText.setText(msg);
                        //Toast.makeText(ctx, "File Upload Complete.",
                        //      Toast.LENGTH_SHORT).show();

                        // recursiveDelete(mDirectory1);

                    }

                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                } catch (Exception e) {

                    // dialog.dismiss();
                    e.printStackTrace();

                }
                // dialog.dismiss();

            } // End else block


        } catch (Exception ex) {
            // dialog.dismiss();

            ex.printStackTrace();
        }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

In Php,

    <?php


     if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
    $uploads_dir = './';
                            $tmp_name = $_FILES['bill']['tmp_name'];
                            $pic_name = $_FILES['bill']['name'];
                            move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
                            }
               else{
                   echo "File not uploaded successfully.";
           }

   ?>
Sign up to request clarification or add additional context in comments.

2 Comments

Hello @Magash. I already have an Asynctask code and a PHP service, My problem is somewhere between, the encoded string is being truncated. I don't know why...
Thanks for including the PHP code! This worked for me. I did add a constructor to the extended AsyncTask class that takes the input file path and the IP address as parameters. with that minor change, the code worked as expected.
0

To upload image using Multipart follow the following steps:

  1. Download httpmime.jar file and add it in your libs folder.

  2. Download http client.jar file and add it in your libs folder.

Call the following method either from a background thread or an AsyncTask.

public void executeMultipartPost() throws Exception {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 75, bos);
        byte[] data = bos.toByteArray();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(
                "YOUR SERVER URL");
        ByteArrayBody bab = new ByteArrayBody(data, "YOUR IMAGE.JPG");

        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("IMAGE", bab);

        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();

        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        System.out.println("Response: " + s);
    } catch (Exception e) {
        // handle exception here
        Log.e(e.getClass().getName(), e.getMessage());
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.