How to track file upload progress?

I need to upload a file to the server and monitor its progress. I need to get a notification about how many bytes are sent each time.

For example, in case of loading, I have:

HttpURLConnection  connection = (HttpURLConnection) m_url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
while ((currentBytes  = stream.read(byteBuffer)) > 0) {                    
    totalBytes+=currentBytes;
    //calculate something...
}

Now I need to do the same for the download. but if you use

OutputStreamWriter stream = new OutputStreamWriter(connection.getOutputStream());
stream.write(str);
stream.flush();

than I can’t get a progress notification, about how many bytes are sent (this looks like an automatic action).

Any suggestions?

thank

+3
source share
6 answers

ChannelSocket. . HTTP , , . , .

+4

.

, ByteArrayOutputStream , Java Content-Length. , . .

+5

, , - FilterOutputStream, (...) .

+2
source

If you want to count the bytes you load, write the objects as arrays of bytes to the output stream, as you do with the input stream.

+1
source

It will be similar to the download method.

OutputStream stream = connection.getOutputStream();
for(byte b: str.getBytes()) {                    
    totalBytes+=1;
    stream.write(b);
    if(totalBytes%50 == 0)
        stream.flush(); //bytes will be sent in chunks of 50
    //calculate something...
}
stream.flush();

Something like that.

0
source

Another approach is to poll the server, which asks how much data is loaded. Perhaps using an identifier or something like that.

POST β†’ / uploadfile

  • ID
  • file

POST -> / queryuploadstate (returns partial size)

  • ID

Of course, for a servlet you need to connect and prevent clustering ...

0
source

All Articles