Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monitor file upload progress?

Tags:

java

post

upload

I need to upload a file to server and monitor it's progress. i need to get a notification how many bytes are sent each time.

For example in case of download 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 upload. but if use

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

than i can't get any progres notification, about how many bytes are sent (it looks like automic action).

Any suggestions?

Thanks

like image 671
Sophie Avatar asked Dec 17 '22 13:12

Sophie


2 Answers

Just set chunked transfer mode and monitor your own writes to the output stream.

If you don't use chunked or fixed-length transfer mode, your writes are all written to a ByteArrayOutputStream before being written to the network, so that Java can set the Content-Length header correctly. This is what made you think it is non-blocking. It isn't.

like image 96
user207421 Avatar answered Jan 01 '23 18:01

user207421


I have used ChannelSocket object. This object allows to do blocking read and write when accessing the server. So i emulated HTTP using this socket and each write request was blocked untill it was done. This way i could follow the actual progress of write transaction.

like image 42
Sophie Avatar answered Jan 01 '23 16:01

Sophie