Get file upload percent complete?

Hi,

I have some code which uploads a photo to a PHP script (code pasted below).

I'd like to give the user some indication as to upload progress - is the code snippet below the place to do that?

Do I just simply use "filelen" and "bytesRead" like this:

    while (bytesRead > 0) {
        println("Uploading " + (bytesRead / filelen) + " percent complete...");
    }

Thanks
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
File theFile = File(pathToPhoto); 
FileInputStream fis = new FileInputStream(new );  
long filelen = theFile.length();
 
... 
 
int bytesAvailable = fis.available(); 
int bufferSize = Math.min(bytesAvailable, MAX_BUF); 
byte[] buffer = new byte[bufferSize]; 
int bytesRead = fis.read(buffer, 0, bufferSize); 
while (bytesRead > 0) { 
    dos.write(buffer, 0, bufferSize); 
    bytesAvailable = fis.available(); 
    bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    bytesRead = fis.read(buffer, 0, bufferSize); 
}

Open in new window

DJ_AM_JuiceboxAsked:
Who is Participating?
 
DerZaubererCommented:
Looks like a good place to me.

- filelen is the total size of the file
- Just sum up the values you get for bytesRead each time you called fis.read().
f.e. int totalRead = 0; ... totalRead += bytesRead ...
- progress might be calculated like this ranging from 0 to 100: int progress = 100 * totalRead / filelen;

If the file size is smaller than MAX_BUF your progress will have one step only.
In this case you could reduce MAX_BUF if it's too large.
0
 
Gurvinder Pal SinghCommented:
Looking at your code, 'bytesRead' is the number of bytes read at a particular instant when file stream read is done.

You need to put one more variable in place to just keep on adding 'bytesRead' value in it inside the loop. Some thing like

int bytesRead = fis.read(buffer, 0, bufferSize);
int totalBytesRead = bytesRead;
while (bytesRead > 0) {
    dos.write(buffer, 0, bufferSize);
    bytesAvailable = fis.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fis.read(buffer, 0, bufferSize);
    totalBytesRead = totalBytesRead  + bytesRead;
    System.out.println("Uploading " + (totalBytesRead / filelen) + " percent complete...");  
}

Let me know if it helped
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.