Flask: Get the size of request.files object

If you don't want save the file to disk first, use the following code, this work on in-memory stream

import os

file = request.files['file']
# os.SEEK_END == 2
# seek() return the new absolute position
file_length = file.seek(0, os.SEEK_END)

# also can use tell() to get current position
# file_length = file.tell()

# seek back to start position of stream, 
# otherwise save() will write a 0 byte file
# os.SEEK_END == 0
file.seek(0, os.SEEK_SET)

otherwise, this will better

request.files['file'].save('/tmp/file')
file_length = os.stat('/tmp/file').st_size

There are a few things to be aware of here - the content_length property will be the content length of the file upload as reported by the browser, but unfortunately many browsers dont send this, as noted in the docs and source.

As for your TypeError, the next thing to be aware of is that file uploads under 500KB are stored in memory as a StringIO object, rather than spooled to disk (see those docs again), so your stat call will fail.

MAX_CONTENT_LENGTH is the correct way to reject file uploads larger than you want, and if you need it, the only reliable way to determine the length of the data is to figure it out after you've handled the upload - either stat the file after you've .save()d it:

request.files['file'].save('/tmp/foo')
size = os.stat('/tmp/foo').st_size

Or if you're not using the disk (for example storing it in a database), count the bytes you've read:

blob = request.files['file'].read()
size = len(blob)

Though obviously be careful you're not reading too much data into memory if your MAX_CONTENT_LENGTH is very large


The proper way to set a max file upload limit is via the MAX_CONTENT_LENGTH app configuration. For example, if you wanted to set an upload limit of 16 megabytes, you would do the following to your app configuration:

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

If the uploaded file is too large, Flask will automatically return status code 413 Request Entity Too Large - this should be handled on the client side.

Tags:

Python

Flask