0

I want to get progress when uploading any image to server. Like 1%, 30% etc. And I used all solutions already provided on different websites, but I get progress for reading of file in writing of DataOutputStream.

Ex.

   while (bytesRead > 0) {
                        dos.write(buffer, 0, bufferSize);
                        sentBytes += bufferSize;
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        if (bytesAvailable > 0) {
                            float progress = ((float) sentBytes / (float) totalAvailable) * 100.0f;
                            if (progress % 10 == 0) {
                                publishProgress(sourceFile, (int) progress);
                            }
                        } else {
                            publishProgress(sourceFile, 100);
                        }
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }

Here i get 100% instantly. But after getting 100% Its still uploading image at this line :

        /*Responses from the server (code and message)*/
            int serverResponseCode = conn.getResponseCode();

I think only this line is only responsible for uploading image. So how can I get actual server-uploading-progress.

Is there any requirement at server side? And my server supports

 connection.setRequestProperty("Content-Type", "application/octet-stream");

Please help me for this. Thanks

NehaK
  • 2,639
  • 1
  • 15
  • 31
  • Possible duplicate of [Android: updating progressbar for file upload](http://stackoverflow.com/questions/11887149/android-updating-progressbar-for-file-upload) – Vadim Kotov Jan 15 '17 at 02:52

2 Answers2

2

Check the Answer provided here:

Your image is also a file, to be clear.

Direct source to Guide:

Community
  • 1
  • 1
David Kasabji
  • 1,049
  • 3
  • 15
  • 32
  • Can you pls mention.. where is solution for my question in your link? – NehaK Jan 09 '17 at 12:16
  • Of course it's not meant as copy-paste, as this site is not here for you to copy-paste solutions, but do a research on your own. We just point you to right direction. – David Kasabji Jan 09 '17 at 12:18
  • Nice! Sorry for not providing everything directly, but in general, for best practice in future, it is best that developers know how to find their solution based upon research: a bit of reading. Yep, annoying, very. – David Kasabji Jan 09 '17 at 13:20
1

I used following method :

Here publishProgress() is to update progressBar.

public String uploadFileWithProgress(String fileName, String serverUrl) {
    Lg.info(DEBUG_TAG, "uploadFile fileName:" + fileName);
    Lg.info(DEBUG_TAG, "uploadFile" + "serverUrl: " + serverUrl);

    HttpURLConnection conn = null;

    File sourceFile = new File(fileName);

    String response = null;

    Lg.info(DEBUG_TAG, "sourceFile: " + sourceFile.toString());

    if (!sourceFile.isFile()) {
    } else {

        HttpURLConnection.setFollowRedirects(false);
        try {

            FileInputStream fileInputStream = new FileInputStream(sourceFile);

            conn = (HttpURLConnection) new URL(serverUrl).openConnection();
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("Accept", "application/json");


            conn.setReadTimeout(100000);
            conn.setConnectTimeout(100000);

            //required --->
            conn.setDoOutput(true);

            long fileLength = sourceFile.length();

            long requestLength = fileLength;
            conn.setRequestProperty("Content-length", "" + requestLength);
            conn.setFixedLengthStreamingMode((int) requestLength);
            conn.connect();
            //<-----

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

            int progress = 0;
            int bytesRead = 0;
            byte buf[] = new byte[1024];
            BufferedInputStream bufInput = new BufferedInputStream(fileInputStream);
            publishProgress(sourceFile, 0);
            lastProgressDone = 0;
            while ((bytesRead = bufInput.read(buf)) != -1) {
                // write output
                out.write(buf, 0, bytesRead);
                out.flush();
                progress += bytesRead;
                // update progress bar
                int progressDoneInPercentage = (int) (progress * 100.0 / requestLength);

                if (progressDoneInPercentage < 100 && progressDoneInPercentage != lastProgressDone) {
                    lastProgressDone = progressDoneInPercentage;
                    publishProgress(sourceFile, progressDoneInPercentage);
                }
            }

            fileInputStream.close();
            // Write closing boundary and close stream
            try {
                out.flush();
            } catch (Exception e) {
            }
            try {
                out.close();
            } catch (Exception e) {
            }

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

            lastProgressDone = 0;
            if (serverResponseCode == 200) {
                publishProgress(sourceFile, 100);
            } else {
                publishProgress(sourceFile, 0);
            }
            InputStream str = conn.getErrorStream();
            Lg.info(DEBUG_TAG, "uploadFile HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if (serverResponseCode == 200) {
                Lg.info(DEBUG_TAG, "uploadFile uploadComplete: " + response);
            } else{
                Lg.info(DEBUG_TAG, "uploadFile Error" + response);
            }

        } catch (OutOfMemoryError e) {
            Lg.printStackTrace(e);
        } catch (Exception e) {
            // Exception
            Lg.error("error in image uploading = " + fileName, e.getMessage());
        } finally {
            if (conn != null) conn.disconnect();
        }
    }
    return response;
}
NehaK
  • 2,639
  • 1
  • 15
  • 31