Python App Engine上传了图像内容类型

Bem*_*mmu 4 python upload google-app-engine image multipart

我知道我可以接受图片上传,方法是将表格发送到App Engine,如下所示:

<form action="/upload_received" enctype="multipart/form-data" method="post">
<div><input type="file" name="img"/></div>
<div><input type="submit" value="Upload Image"></div>
</form>
Run Code Online (Sandbox Code Playgroud)

然后在Python代码中我可以做类似的事情

image = self.request.get("img")
Run Code Online (Sandbox Code Playgroud)

但是,如何在以后向用户显示该图像时,如何确定该图像的内容类型?似乎最强大的方法是从图像数据本身中解决这个问题,但是如何轻松地解决这个问题呢?我没有在google.appengine.api图片包中看到任何合适的内容.

我应该只在我自己的代码中查找魔术图像标题,还是已经有某种方法可以在某处?

编辑:

这是我最终使用的简单解决方案,似乎适用于我的目的,并避免必须将图像类型存储为数据存储中的单独字段:

# Given an image, returns the mime type or None if could not detect.
def detect_mime_from_image_data(self, image):
    if image[1:4] == 'PNG': return 'image/png'
    if image[0:3] == 'GIF': return 'image/gif'
    if image[6:10] == 'JFIF': return 'image/jpeg'
    return None
Run Code Online (Sandbox Code Playgroud)

Nic*_*son 5

而不是使用self.request.get(fieldname),请使用self.request.POST [fieldname].这将返回一个cgi.FieldStorage对象(有关详细信息,请参阅Python库文档),该对象具有"filename","type"和"value"属性.