简体   繁体   中英

Java servlet and Ajax uploading files progress bar

Currently, i using XmlHttpRequest to uploading files to the server using HTML5 capabilities.

There's progress bar:

xhr.upload.addEventListener('progress', function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log(done);
});

... everything works fine, but it doesn't consider processing the file by server. So it shows 100% uploaded even when file weren't created yet.

The file receiver is Java servlet, which able to response only after return. So here's no way to count the percents left by its response.

Whether there are ways around it?

If the processing the server does takes a long time and you want to give feedback while it happens, here's a rough outline of a solution. This will take a while to implement so it's only really worth doing if the processing is slow.

  1. Modify your servlet to do its work asynchronously, and return a 201 Accepted response to the client.
  2. As the server processes the file, set the progress on an object, typically a ConcurrentHashMap injected with Spring if that's what you're using.
  3. Expose an API that queries the current progress of the task without blocking for it to complete.
  4. In your javascript, poll this API until the task completes, and show the progress.

You can return a tracking ID in the response at step 1 if you need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM