Sharing / uploading image to server

1 min read

Dear Reader

Few days back me and my students were working on an application in which we had a requirement to share an image to a Server.

Since this was a sort of Chat Application so it was quintessential functionality some how recipient gets notified of shared image  whenever image is shared with recipient. So recipient can fetch the image from Server,  on getting a notification.

 

So Let use the famous conceptual way Divide and Rule / Conquer method. Lets divide our big problem into two or more sub problems.

We can divide the problem as

  1. Sharing / uploading image to server
  2. Getting FCM notification from Server
  3. When notification arrives at Client end , Fetch image from Server.

 

Further In this post we gonna see how to upload image to server

 

public class ChatImageMessageUploadTask extends AsyncTask<Void ,Void ,Boolean> {


    StringBuffer responseData = new StringBuffer();
    Bitmap bitmap = null;

    String urlString =
            "url to upload data";


    public ChatImageMessageUploadTask(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {

          

            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");



            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,90, bos);

            String encodeImage = Base64.encodeToString(bos.toByteArray(), Base64.NO_WRAP | Base64.URL_SAFE);
            SharedPreferences sharedPreferences = getSharedPreferences(
                    "chatpreference", Context.MODE_PRIVATE
            );
            String logedInUserName = sharedPreferences.getString("loggedInUserName", null);
            String logedInUserEmail = sharedPreferences.getString("loggedInUserEmail", null);



            String postData = "controlVar=42&senderemailid="+logedInUserEmail+"&recipientemailid="+recipientEmail+"&imagedata="+encodeImage;





            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(postData);
            writer.flush();
            writer.close();
            os.close();


            int code = urlConnection.getResponseCode();

            InputStream inputStream = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                responseData.append(line);
            }
            return true;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if(aBoolean) {
            if(responseData != null && !responseData.toString().equalsIgnoreCase("")){
                Log.v("TAG",responseData.toString());

            }
        }
    }
}

 

Below lines are important

 

 ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,90, bos);

            String encodeImage = Base64.encodeToString(bos.toByteArray(), Base64.NO_WRAP | Base64.URL_SAFE);

 

There was a bug in Base64 encoding due to which uploaded image on server was corrupted. So options Base64.NO_WRAP | Base64.URL_SAFE are used.

 

Rest other things like uploading image via HTTPURLConnection and posting data to server is trivial code.

 

Happy Coding !