Flask file upload limit

rottentomato56 picture rottentomato56 · Nov 11, 2013 · Viewed 14.1k times · Source

I have a file upload handler for multiple file uploads, and have set the MAX_CONTENT_SIZE. The docs mention that Flask throws a 413 exception when the total file size exceeds the limit, so I've also written a 413 error handler with a custom 413 page. However, when testing the file upload, I can see that the 413 error is definitely thrown, but the connection seems to break everytime instead of rendering my error page. FYI, I'm using the Flask dev server currently.

Code:

app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024    # 50 Mb limit

@app.route('/upload', methods=['POST'])
def upload_files():
    if request.method == 'POST':
       uploaded_files = request.files.getlist('uploaded_files[]')

       # do some stuff with these files



@app.errorhandler(413)
def error413(e):
    return render_template('413.html'), 413

UPDATE:

Ok strange, this problem seems to only occur when using the Flask dev server. I'm testing it on Apache, and my 413 error page renders fine.

Answer

Grey Li picture Grey Li · Feb 17, 2021

Use a production WSGI server will solve this problem (e.g. Gunicorn, Waitress). Below is a simple timeline of this issue.

2015

In this snippet (gone) that posted by Armin Ronacher, he said:

You might notice that if you start not accessing .form or .files on incoming POST requests, some browsers will honor this with a connection reset message. This can happen if you start rejecting uploads that are larger than a given size.

Some WSGI servers solve that problem for you, others do not. For instance the builtin Flask webserver is pretty dumb and will not attempt to fix this problem.

2018

I added a tip in the Flask's file uploading docs (flask #2662):

Connection Reset Issue

When using the local development server, you may get a connection reset error instead of a 413 response. You will get the correct status response when running the app with a production WSGI server.

2021

I think/hope it will be fixed in Werkzeug in the near future (werkzeug #1513).