How can a servlet determine when a download has been canceled?

Here is the javascript side code to download based on the form:

iframe.setAttribute('src', 'javascript:false;'); 

I use the above code to cancel the incomplete download associated with an input element placed in an iframe.

I use the code below to cancel the download sent via XHR:

 myxhr.abort(); 

In both cases, no more bytes are sent to the servlet. The part I'm struggling with is on the servlet side. Currently, I cannot determine the way for the servlet instance to determine if the user is canceling the download. This is important, otherwise the servlet will continue and process the partially downloaded file as if it were valid.

How can I determine through HttpServletRequest if the user cancels the download?

+4
source share
3 answers

A POST request with data contains a Content-Length header that tells you the size of the data that will be downloaded.

So, when the data stops arriving on your server and the size of the received data is less than expected - this will mean that the user (or some network failure) canceled the download.

+2
source

If the download was canceled, the browser will close the connection, which will result in an IO exception on the servlet side. For example, in Tomcat it will say “Connection reset by peer”, and this is a ClientAbortException exception. Other servers exchange IOException in different ways. The point simply catches an IOException, and you should be able to handle it as you wish.

Using content lengths is not reliable because the HTTP specification does not require content length headers for POST - or for GET for this question. Point, if you are not sure that your Javascript XHR explicitly sets the header, this method will not work.

Alternatively, you can calculate it yourself and install it to make sure, or even better, add your own character stream to the end of the placed data in XHR, some unique character string, for example. 'jh923k49sk $ 2 #%'. In the server, disable the last 14 characters of the incoming message and check it for string. If this is the same, you know that they did not cancel.

+1
source

I don’t see how you can tell, just because the request flow has ended, regardless of whether this is done or canceled. There should be a separate HTTP request indicating a cancellation, which should include some token or identifier associated with the download, since HTTP is stagnant and idempotent.

0
source

Source: https://habr.com/ru/post/1402544/


All Articles