Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 479
  • Last Modified:

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

0
DJ_AM_Juicebox
Asked:
DJ_AM_Juicebox
2 Solutions
 
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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now