namit
namit

Reputation: 6957

can we count the upload filesize before uploading in python-flask

I have a simple flask app where i am uploading single file but with file size of less than 5MB
for that i have defined
if request.content_length < 5.250e+6: ## setting upload limit to 5MB test case in my flask-app; but this is verifying the file size after uploading it; or may be i am wrong.
so is there any way to get the file size before uploading it???

Here is python solution on python+GAE, but i am new to python web framework; i know very little in flask
and this solution is based on webapp2 which is very complicated for me and also its on GAE; that is another story. so can anyone generate its flask equivalent or any other possible way to do it in flask???

Upvotes: 2

Views: 7114

Answers (2)

Audrius Kažukauskas
Audrius Kažukauskas

Reputation: 13543

Flask is able to limit file size while upload is in progress, see the documentation. All you need is to set MAX_CONTENT_LENGTH when configuring your app.

Upvotes: 5

kmonsoor
kmonsoor

Reputation: 8109

This is a bit expanded version of Audrius Kažukauskas's answer:


so is there any way to get the file size before uploading it???

No. As per werkzeug's documentation that Flask use to handle uploaded file, you cannot verify the content-size before uploading is NOT guaranteed by all browsers. Only the total content-length of all the data in the request is guaranteed to be there. web-browsers. Hence, Flask/werkzeug can enforce checking only after file-upload.

However, to avoid crashing of your web-server from memory-overflow, you can and should limit the upload-able size. Here comes the config variable MAX_CONTENT_LENGTHwhich you can mention in app's config file.

Example usage from Flask doc:

from flask import Flask, Request

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # for 16MB max-limit.

However, for any serious application, you should consider using the Flask-plugin Flask-Uploads which allows more advanced options such as white-listing and black-listing certain file-types, type-based upload rules, configurable upload destinations etc.

You can question why should i go for the extra extension.
Because, Flask is a micro-framework. Not a do-it-all framework.

Upvotes: 4

Related Questions