• Post Reply Bookmark Topic Watch Topic
  • New Topic

Apache commonsFileUpload - preventing huge files from being uploaded  RSS feed

adam spline
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using Apache Commons FileUpload with Tomcat 6. I have a standard requirement in which users can upload images via an html web form. I am trying to prevent users from uploading huge files. I would like to be able to cut off the files if they are too big without having the entire large file be uploaded before it is rejected. This is to prevent abuse. I know I can use some html5 validation on the client, but I need a solution on the server to prevent abuse.

Here is what I have tried and does not work for me:

1) Setting the setFileSizeMax and setSizeMax of ServletFileUpload requires the entire file to be uploaded before this exception is thrown. Thus, a 1 GB file will completely upload, and then when it is parsed it throw this exception.

2) Checking the request's content length does not prevent the entire file from being uploaded

3) Setting the maxPostSize in server.xml does not work for content-type: multipart/form-data and this value is ignored in this situation. See this post http://tomcat.10.n6.nabble.com/The-purpose-of-maxPostSize-td2158253.html

4) The best I have so far is to use the FileUpload Streaming API http://commons.apache.org/fileupload/streaming.html. Using this method we are able to process the bytes as they come in. And if the number of bytes gets too big, we simply stop writing them to disk. However, I am not able to stop the upload. When I try to close the client's inputstream, the stream does not close, but blocks and waits until the entire file is uploaded. Similarly, if I not not close the inputstream (which seems to be bad practice) and just "return" out of the servlet, the client still continues to upload the file, and it appears that tomcat is still happily accepting the bytes, even though the bytes are not written to file.

This seems like a standard situation, but I am not able to find a clear solution. Any help will be appreciated. Thanks!

It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!