java 文件上传终止_文件上传:服务器如何终止客户端继续上传

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

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

写道

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控件),如果放任其不管,会发现客户端内存不断攀升(并非浏览器进程),服务端内存也不断攀升,直至浏览器失去响应。(因此并非上述帖子中提到

的:如果大小超限,服务端在抛出异常后,会将读取的数据丢弃,因为实际看来这些资源并没有被立即释放)。

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值