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

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

问题描述

我想控制上传图片的大小是否大于最大文件上传限制.我试过这个:

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

它打印了0.我究竟做错了什么?我应该从它的临时路径中找到这个图像的大小吗?有没有类似 PHP 的 $_FILES['foo']['size'] 在 Python 中的东西?

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?

推荐答案

这里有几点需要注意 - content_length 属性将是浏览器报告的文件上传的内容长度,但不幸的是许多浏览器不要发送这个,如 docs来源.

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.

至于您的 TypeError,接下来要注意的是,500KB 以下的文件上传作为 StringIO 对象,而不是假脱机到磁盘(再次查看这些文档),因此您的 stat 调用将失败.

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 是拒绝大于您想要的文件上传的正确方法,如果您需要它,确定数据长度的唯一可靠方法是在您处理上传后计算出来 - 要么 stat.save()d 之后的文件:

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)

但显然要小心,如果 MAX_CONTENT_LENGTH 非常大,不要将太多数据读入内存

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天全站免登陆