作者:谷饶潮流服装HLGC | 来源:互联网 | 2023-06-03 11:22
Hereissomecodeonthejavascriptsideforform-baseduploads:以下是javascript端的一些代码,用于基于表单的上传:ifr
Here is some code on the Javascript side for form-based uploads:
以下是Javascript端的一些代码,用于基于表单的上传:
iframe.setAttribute('src', 'Javascript:false;');
I'm using the code above to cancel an in-progress upload associated with an input element placed in an iframe.
我正在使用上面的代码来取消与放置在iframe中的输入元素相关联的进行中上传。
I'm using the code below to cancel an in-progress upload sent via XHR:
我正在使用以下代码取消通过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 can't figure out a way for the servlet instance to determine if the user has cancelled the upload. This is critical, otherwise the servlet will go on and process the partially uploaded file as if it is valid.
在这两种情况下,都不会向servlet发送更多字节。我正在努力的部分是在servlet方面。目前,我无法找到servlet实例确定用户是否取消上传的方法。这很关键,否则servlet将继续处理部分上载的文件,就好像它是有效的一样。
How can I determine, via the HttpServletRequest, if a user has cancelled the upload?
如何通过HttpServletRequest确定用户是否取消了上传?
3 个解决方案
1
If the upload has been cancelled the browser will close the connection, resulting in a an IO exception on the servlet side. For example, in Tomcat it will say "Connection reset by peer" and this is a ClientAbortException. Other servers wrap the IOException differently. Point is just catch the IOException and you should be able to handle it as you wish.
如果上传已被取消,浏览器将关闭连接,导致servlet端出现IO异常。例如,在Tomcat中,它将显示“Connection by peer”,这是ClientAbortException。其他服务器以不同方式包装IOException。 Point只是捕获IOException,你应该能够按照自己的意愿处理它。
Using content-length is not reliable because the HTTP spec does not require content-length headers for POSTs - or for GETs for the matter. Point is, unless you are sure your Javascript XHR sets the header explicitly, this method won't work.
使用内容长度是不可靠的,因为HTTP规范不要求POST的内容长度标题 - 或者GET的内容长度标题。重点是,除非您确定您的Javascript XHR明确设置了标头,否则此方法将无效。
Alternatively you could calculate it yourself and set it to be sure, or even better append your own character stream to the end of a the posted data in the XHR, some unique string of characters, e.g. "jh923k49sk$2#%'. In the servlet, snip off the last 14 characters of the inbound message and check it against the string. If it is the same you know they didn't cancel.
或者你可以自己计算并设置它以确保,或者甚至更好地将你自己的字符流附加到XHR中的发布数据的末尾,一些独特的字符串,例如“jh923k49sk $ 2#%'。在servlet中,剪掉入站消息的最后14个字符并检查字符串。如果它是相同的,你知道它们没有取消。