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: ##
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.
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_LENGTH
which 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.