http 上传中止

参考文献:http://www.iteye.com/topic/1020537

该场景为:当上传文件不满足要求(服务器端检查:如文件超过大小限制,扩展名不正确等),服务器在等待文件上传完成之前立即返回,目的是终止浏览器继续上传。

 

但是在实际应用中,并不能按上述预想的场景实现,实际情况是:服务器在文件上传过程中关闭响应输出流立即返回,并不能终止浏览器上传,上传的连接依然被保持,浏览器表现为依然在上传文件。

 

Google后,有一篇帖子或多或少说明了这个问题:http://stackoverflow.com/questions/3107631/how-to-close-a-http-connection-from-the-httpservlet

 

写道
ASK:

I'm running a servlet in Tomcat 6.0.26. The servlet accepts file upload from the client by HTTP POST. I'd like to stop the file uploading from the HttpServlet side. I tried the following methods with no luck:

1. close the request inputstream
2. send error code HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE and flush response
3. do 1 and 2 in a Filter

I googled but found no direct answers. Please advise solutions.

Thanks.


Answer:

This is not possible using the standard Servlet nor Commons FileUpload API's. Basically, to be able to abort the connection immediately, you should grab the underlying socket physically and close it. However, this socket is controlled by the webserver. See also this related question:How to explicitly terminate http connection from server with no response header.

Little tests have however confirmed that Commons FileUpload doesn't buffer up the entire file in memory when its size exceeds the limit. It will read the input stream, but just ignore and throw away the read bytes (also the ones which are already read). So memory efficiency isn't necessarily the problem here.

To fix the real problem, you'd basically like to validate the file size in the client side rather than the server side. This is possible with a Java Applet or a Flash Application. For example, respectivelyJumpLoaderandSWFUpload.
 

 

测试过程发现,如果上传巨大的文件,服务端(commons-fileupload 实现)会抛出 FileUploadBase$SizeLimitExceededException ,并且服务端立即返回响应;但是浏览器显示仍在上传中(普通html file控件),如果放任其不管,会发现客户端内存不断攀升(并非浏览器进程),服务端内存也不断攀升,直至浏览器失去响应。(因此并非上述帖子中提到 的:如果大小超限,服务端在抛出异常后,会将读取的数据丢弃,因为实际看来这些资源并没有被立即释放)。

 

再次询问有没有好的解决的办法?

这和http协议有关。
问题的根本在于:在客户端发起http请求完毕之前,压根就没法让客户端终止上传。因为对于这次交互来说,所有的上传数据都属于一个请求之内。
两种做法: 
1: 关闭socket连接

2: 获取上传内容后就直接丢掉   


每个httpserver只有一个listen socket,这个一直存在。
当accept时,返回一个socket,这个是connection socket, 每个TCP连接一个connection socket., 浏览器的每次请求都会有一个connection socket被建立


客户端向服务器发送数据,服务器根据socket,来进行通信。但是,如果客户端向服务器发送的数据量比较大,服务器端没有接收完毕时,可以writeback吗?

我猜测即使可以written back,浏览器也不会反应,因为它正在写数据呢!!
这样,就造成了浏览器工作的不正常!!!

服务器writte back后,就会把socket清掉,等待下一次的http连接.......

upload未完成时能不能通知浏览器,完全由http协议实现来决定,http中有关于这个的协定吗??
查找一下!!!( HTTP-the definitive guide这本书中,说这个自由的,也就是http协议中并未做严格的规定)


浏览器向服务器发送数据时,如果服务器不接收,客户端的write函数就block住了,这样就不会返回,也就无法读取服务器写回来的数据,这样有可能造成浏览器的报错!!!!

 written@yazhouren
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值