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

前端 未结 2 916
滥情空心
滥情空心 2021-01-23 07:13

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: ##

相关标签:
2条回答
  • 2021-01-23 07:52

    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.

    0 讨论(0)
  • 2021-01-23 08:02

    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.

    0 讨论(0)
提交回复
热议问题