Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: Get the size of request.files object

Tags:

python

flask

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"]) def newPhoto():      form_photo = request.files['post-photo']     print form_photo.content_length 

It printed 0. What am I doing wrong? Should I find the size of this image from the temp path of it? Is there anything like PHP's $_FILES['foo']['size'] in Python?

like image 454
saidozcan Avatar asked Apr 02 '13 19:04

saidozcan


People also ask

What is request files flask?

Flask facilitates us to upload the files easily. All we need to have an HTML form with the encryption set to multipart/form-data. The server-side flask script fetches the file from the request object using request. files[] Object. On successfully uploading the file, it is saved to the desired location on the server.

How do you find the filename on a flask?

Once you fetch the actual file with file = request. files['file'] , you can get the filename with file. filename .


2 Answers

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

like image 96
DazWorrall Avatar answered Oct 05 '22 01:10

DazWorrall


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'] file.seek(0, os.SEEK_END) file_length = file.tell() 

otherwise, this will better

request.files['file'].save('/tmp/file') file_length = os.stat('/tmp/file').st_size 
like image 21
Steely Wing Avatar answered Oct 05 '22 01:10

Steely Wing