1

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.

Tofeeq Ahmad
  • 11,935
  • 4
  • 61
  • 87
chiranjib
  • 5,288
  • 8
  • 53
  • 82

2 Answers2

1

Although it is some tricky but you can achieve it.I found this question that is really helpful .So please go though this and let me know

This is the details Discussion and Code

Community
  • 1
  • 1
Tofeeq Ahmad
  • 11,935
  • 4
  • 61
  • 87
0

The following link solved my problem

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

chiranjib
  • 5,288
  • 8
  • 53
  • 82