Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

java - Browser download complete event

We've been looking for a while for an answer to this, but haven't found a solution.

We have a web server, which allows the user to download files (pdfs), which are dynamically-generated and served from servlets. We'd like to know when a download has completed (and how: was it successful, did it fail, did the user cancel?).

Is there a way to know this without user input? These files are relatively small so no progress-bar functionality is needed, but we need some sort of "end-hook" which reports back when the download has finished. Is this possible?

[edit] What capability would there be on the browser-side that can detect end-of-download and report back to the server via ajax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get a pretty good idea from the server which is connected to the browser directly (the endpoint of TCP connection). The server will get IO error when user cancels download or encounters any network problem. So if you can run the server directly (without proxies). You can do something like this,

  try {
      response.setContentType("application/pdf");
      response.setContentLength(bytes.length);
      ServletOutputStream ouputStream = response.getOutputStream();
      ouputStream.write(bytes, 0, bytes.length);
      ouputStream.flush();
      ouputStream.close();
      logger.info("PDF " + fileName + " sent successfully");
  } catch (Exception e) {
      logger.error("PDF " + fileName + " error: " + e.getMessage());
      throw e;
  }

However, there is still a small chance that the user may not see the PDF in browser after successful download. ACK from browser will be best approach. You can't do that if PDF is displayed by browser directly. You have to use some kind of Javascript PDF viewer and add a call back to server when it's displayed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...