Python:检查上传的文件是否为jpg [英] Python: Check if uploaded file is jpg

查看:687
本文介绍了Python:检查上传的文件是否为jpg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查用户上传的文件是否是真正的Python文件(Google App Engine)?

How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?

这是我现在得到的:

脚本通过HTML Form Post接收图片,并由以下代码处理

Script receives image via HTML Form Post and is processed by the following code

...
incomming_image = self.request.get("img")
image = db.Blob(incomming_image)
...

我找到了mimetypes.guess_type,但它不适用于我。

I found mimetypes.guess_type, but it does not work for me.

推荐答案

如果您需要的不仅仅是查看扩展,还有一种方法是读取JPEG标头,并检查它是否与有效数据匹配。格式为:

If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is:

Start Marker  | JFIF Marker | Header Length | Identifier
0xff, 0xd8    | 0xff, 0xe0  |    2-bytes    | "JFIF\0"

所以一个快速识别器是:

so a quick recogniser would be:

def is_jpg(filename):
    data = open(filename,'rb').read(11)
    if data[:4] != '\xff\xd8\xff\xe0': return False
    if data[6:] != 'JFIF\0': return False
    return True

然而,这并不能捕捉到任何不正确的数据。如果您想要更强大的检查,可以尝试使用 PIL 加载。例如:

However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with PIL. eg:

from PIL import Image
def is_jpg(filename):
    try:
        i=Image.open(filename)
        return i.format =='JPEG'
    except IOError:
        return False

这篇关于Python:检查上传的文件是否为jpg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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