1

I have AsynscTask which help me to upload image to server and it's works perfectly without any issues but now i want to show upload percentage and it's total size uploaded to user. For image uploading i am using Base64 Image which is converted into String before upload and showing percentage is an issue for me i googled but not able to find solution for Base64 image upload percentage.

Here is my AsyncTask

private class uploadImage extends AsyncTask<Void,Void,String> {
    private static final String uploadImage_URL="https://192.168.1.10/Android/upload.php";
    BufferedReader reader;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

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

    @Override
    protected String doInBackground(Void... voids) {
        Bitmap base64Bitmap = BitmapFactory.decodeFile(finalPath);
        String Base64Image = App_Functions.Convert_To_Base64(base64Bitmap);
        int length = Base64Image.length();

        try {
            String data = URLEncoder.encode("userId", "UTF-8") + "=" + URLEncoder.encode(Session.getUserID(), "UTF-8");
            data += "&" + URLEncoder.encode("ImageBase64", "UTF-8") + "=" + URLEncoder.encode(Base64Image, "UTF-8");
            //data += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("coverphoto", "UTF-8");
            URL url=new URL(uploadImage_URL);
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(10000);
            connection.connect();
            int imagePayload = Base64.decode(Base64Image,Base64.NO_WRAP).length;
            Log.d(TAG,"Image Pay Load "+imagePayload/1024);

            OutputStream outputStream = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.flush();
            writer.close();
            outputStream.close();

            Log.d(TAG, "Response Code " + connection.getResponseCode());
            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                StringBuilder stringBuffer = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    stringBuffer.append(line);
                    Log.d(TAG, "Appending JSON into String Buffer");
                }
                Log.d(TAG, "JSON Received " + stringBuffer);
                JSONObject jsonObject = new JSONObject(stringBuffer.toString());

                String serverResponse = jsonObject.getString("userImageUpload");
                String pathOfImage,pathOfCover;
                if (serverResponse.equals("Image Uploaded")){
                    return "Success";
                }else {
                    return "Fail";
                }

            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);      
        if (result!=null){
            if (result.equals("Success")){
                //progressBar.dismiss();

            }else {
                Toast.makeText(MyApplication.getmContext(), "Fail to upload image. Please try again.", Toast.LENGTH_SHORT).show();
                //progressBar.setProgress(0);
                //progressBar.setMessage("Image Upload Failed");
                //progressBar.setCancelable(true);
            }
        }

        /*DialogFragment interest=new Interest_Grid();
        interest.show(getFragmentManager(),"UploadImage");     */

    }
Ritu
  • 518
  • 2
  • 12
  • 35
  • I think this method from BufferedWriter may help: *write(String s, int off, int len)* https://developer.android.com/reference/java/io/BufferedWriter.html#write(java.lang.String,%20int,%20int) But you need to specify the part's length for each call, calculate yourself the written characters inside the loop... – Phong Nguyen Oct 23 '19 at 02:38
  • You can achieve this using `retrofit`. [see this answer](https://stackoverflow.com/a/33384551/4854891) – Jakir Hossain Oct 23 '19 at 04:49
  • I dont want to use any library just for showing percentage. Isn't possible with my current code? – Ritu Oct 23 '19 at 08:10

0 Answers0