views:

244

answers:

4

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.

+1  A: 

Question is much or less a duplicate of http://stackoverflow.com/questions/157132/aborting-upload-from-a-servlet

Did you try using Jakarta Commons FileUpload?

There is a setFileSizeMax method in server object representing a file upload from a request.

fg
I tried FileUpload but it doesn't work for me. What I want is to stop the upload process totally. But with FileUpload's setFileSizeMax, it won't stop the client uploading the whole content to the server(which costs server's bandwidth).
Jason
@Jason: You need to use [streaming mode](http://commons.apache.org/fileupload/streaming.html). It by default reads file into memory/tempdisk first.
BalusC
@BalusC: What I want is to terminate the client's upload process. Streaming mode will still receive the whole file before do anything about it. It's just too late.
Jason
+1  A: 

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, respectively JumpLoader and SWFUpload.

BalusC
+1  A: 

Hi,

here is some crazy workaround: you can write (or find somewhere) some firewall standalone application based on Sockets that handles HTTP request, parses headers and if the request matches some your custom conditions - firewall forwards it to Tomcat, otherwise returns HTTP error response. Or you can try to tune Apache <-> Tomcat with some Apache rules.

Regards, Dmytro

Dmytro Pishchukhin
A: 

This is not possible using standard APIs. And you're violating some protocol standards/RFC if you do. So why would you do that?

Instead, send a "Connection: close" response (http header) with no http body.

MRalwasser