Search code examples
pythonfile-uploadcherrypy

Preventing files with size greater than some limit from being uploaded


I set up a server using cherrypy to which files can be uploaded. However, I want to prevent files being uploaded if they exceed a certain size. I searched a bit but was not able to find out an answer. Is there a way to achieve this with cherrypy or in general ?


Solution

  • cherrypy._cpserver.Server.max_request_body_size is probably what you want.

    Before an HTTP client uploads a file, in the HTTP headers they must specify the size of their message body. Based on that you can immediately reject the upload attempt with a HTTP 413 Request Entity Too Large error message.

    It's possible to circumvent this by saying a certain amount and then uploading more - but most servers are smart enough to stop reading when they've hit the maximum they intend on accepting from a client.

    Unfortunately, this isn't always the case because there's also a method of HTTP upload called 'Chunked encoding', in which the client (or server, depending on which way it's going) is not required to advertise the size of their upload. You mostly see this on the server side as a way to stream data to clients.