If you expect really large file uploads, then it would be nice to report to your users, how much is already received. Even HTML pages allow implementing a progress bar by returning a multipart/replace response, or something like that. Tracking the upload progress may be done by supplying a ProgressListener
.
ProgressListener
is called quite frequently, depending on the servlet engine and other environment factors it may be called for any network packet. In other words, your ProgressListener
may become a performance problem! A typical solution might be to reduce the activity of ProgressListener
to only emit a message if the number of megabytes has changed beyond a range. The following example shows a ProgressListener
which implements this solution. We will probably want to communicate the progress to the progress bar on the client. The Real-time server push recipe in Chapter 11, Advanced Tips, can be used as a starting point for implementing pushing updates to the client.
/Create a progress listener ProgressListener progressListener = new ProgressListener(){ private long megaBytes = -1; // only update the percent if more than a MB has been uploaded. public void update(long pBytesRead, long pContentLength, int pItems) { long mBytes = pBytesRead / 1000000; if (megaBytes == mBytes) { return; } megaBytes = mBytes; // compute percent uploaded. if(pContentLength > 0) { float percent = pBytesRead / pContentLength; // percent needs to be communicated to the client // progress bar } } };