Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7742111
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T09:12:00+00:00 2026-06-01T09:12:00+00:00

The following code uploads file to the server display progressdialog with percentage without any

  • 0

The following code uploads file to the server display progressdialog with percentage without any issue.

protected boolean uploadFile(String serverUrl, String filePath) {
            HttpURLConnection connection = null;
            DataOutputStream outputStream = null;
            DataInputStream inputStream = null;
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int serverResponseCode;
            String serverResponseMessage;
            boolean uploadstatus = false;
            int count;
            long lengthOfFile;

            try {
                urlServer = serverUrl;
                pathFile = filePath;

                FileInputStream fileInputStream;
                fileInputStream = new FileInputStream(new File(pathFile));
                URL url = new URL(urlServer);
                connection = (HttpURLConnection) url.openConnection();
                // Allow Inputs & Outputs
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);
                // Enable POST method
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                outputStream = new DataOutputStream(connection.getOutputStream());
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes(lineEnd);
                lengthOfFile = new File(filePath).length();// length of file
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[1024];
                bytesRead = 0;
                String progressMsg = "";
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    total += bytesRead;
                    progressMsg = new StringBuffer(" ").append((int) ((total * 100) / totalLengthOfFile)).toString();
                    prgressBarMsg[0] = progressMsg;
                    publishProgress(prgressBarMsg);
                    outputStream.write(buffer);// , 0, bufferSize);
                }
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                // Responses from the server (code and message)
                serverResponseCode = connection.getResponseCode();
                serverResponseMessage = connection.getResponseMessage();
                if (serverResponseCode == 200)// HTTP OK Message from server
                {
                    uploadstatus = true;
                } else {
                    uploadstatus = false;
                }
                // this block will give the response of upload link
                try {
                    BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    while ((line = rd.readLine()) != null) {
                        // Log.i("ARC", "RES Message: " + line);
                    }
                    rd.close();
                } catch (IOException ioex) {
                    // Log.e("ARC", "error: " + ioex.getMessage(), ioex);
                }
                fileInputStream.close();
                outputStream.flush();
                outputStream.close();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                connection.disconnect();
            }
            return uploadstatus;
        }

The following code using Apache also uploads file to the server & is recommended for uploading files with larger sizes(it is more stable) but it is bit slower in terms of time taken to upload compared to the above code. I found the code using HttpURLConnection throw exception when file size exceeds 20 MB so I am now implementing the file upload code using Apache.

protected boolean uploadFile(String serverUrl, String filePath) {
        boolean status = false;
        try {
            File file = new File(filePath);
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(serverUrl);
            FileBody bin = new FileBody(file);
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
            reqEntity.addPart("myfile", bin);
            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder responseMsg = new StringBuilder();
                while ((sResponse = reader.readLine()) != null) {
                    responseMsg = responseMsg.append(sResponse);
                }
            }
            status = true;
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }
        return status;
    }

I want to display progressdialog with percentage for the file upload using Apache code .
How can we get the bytesRead value used to calculate the progressdialog percentage for the Apache code ?

Any suggestions/hints for implementing the same will be helpul.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T09:12:02+00:00Added an answer on June 1, 2026 at 9:12 am

    The following link solved my problem

    http://toolongdidntread.com/android/android-multipart-post-with-progress-bar/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code that uploads the file to the server by making
Please can someone help? I have the following code which uploads a file to
Following is the java code on android side. It uploads file from the smartphone
I have the following code to upload a file to the server. For some
I am using the following code to upload the file <asp:UpdatePanel ID=UpdatePanel18 runat=server> <ContentTemplate>
I currently use the following code to upload one file to a remote server:
I have the following code which uploads images to a rackspace cdn account. error_reporting(E_ALL);
Following code is from a sample of playframework-2.0: /** * Display the dashboard. */
I have index.php which uploads a file to server and sets several PHP variables
Hi I have the following piece of code to upload a file to Sharepoint.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.