Flask:获取request.files对象的大小 [英] Flask: Get the size of request.files object

查看:725
本文介绍了Flask:获取request.files对象的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <$ c我想获得上传图像的大小来控制它是否大于最大文件上传限制。 $ c $ @ app.route(/ new / photo,methods = [POST])
def newPhoto():

form_photo = request.files ['post-photo ']
print form_photo.content_length

打印 0 我在哪里做错了?我应该从它的温度路径找到这个图像的大小? Python中没有像PHP的 $ _ FILES ['foo'] ['size'] 吗?

解决方案

在这里有几件事要注意 - content_length属性将是浏览器报告的文件上传的内容长度,但不幸的是许多浏览器不发送这个文档资源



至于TypeError,接下来要注意的是在500KB以下的文件上传作为 StringIO对象存储在内存中,而不是假脱机到磁盘(见docs再次),所以你的stat调用将失败。
$ b

MAX_CONTENT_LENGTH是拒绝大于你想要的文件上传的正确方法,如果你需要它,唯一可靠的wa y确定数据的长度是在处理完上载之后计算出来的 - 或者在 .save() d it

  request.files ['file']。save('/ tmp / foo')
size = os.stat ('/tmp/foo').st_size

或者如果您不使用磁盘例如将其存储在数据库中),计算您读取的字节:

  blob = request.files ['file'] .read()
size = len(blob)

虽然显然要小心,如果MAX_CONTENT_LENGTH非常大,则不会将太多的数据读入内存。

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 Where am i doing wrong? Should i find the size of this image from the temp path of it? Isn't there anything like PHP's $_FILES['foo']['size'] in Python?

解决方案

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

这篇关于Flask:获取request.files对象的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆