Flask: Get the size of request.files object

后端 未结 5 1336
旧巷少年郎
旧巷少年郎 2020-12-03 01:15

I want to get the size of uploading image to control if it is greater than max file upload limit. I tried this one:

@app.route(\"/new/photo\",methods=[\"POST         


        
5条回答
  •  没有蜡笔的小新
    2020-12-03 02:02

    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

提交回复
热议问题