4

我知道我可以通过使用 POST 到 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>

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

image = self.request.get("img")

但是,当稍后向用户显示此图像时,如何确定该图像的内容类型应该是什么?似乎最可靠的方法是从图像数据本身中找出这一点,但如何轻松获得呢?我在 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
4

3 回答 3

5

Instead of using self.request.get(fieldname), use self.request.POST[fieldname]. This returns a cgi.FieldStorage object (see the Python library docs for details), which has 'filename', 'type' and 'value' attributes.

于 2009-09-11T07:27:44.533 回答
2

Try the python mimetypes module, it will guess the content type and encoding for you,

e.g.

>>import mimetypes

>>mimetypes.guess_type("/home/sean/desktop/comedy/30seconds.mp4")

('video/mp4', None)

于 2009-09-30T02:14:28.347 回答
0

根据我的研究,除了 Internet Explorer(至少是版本 6)之外的浏览器,通过使用文件的扩展名来确定文件 mime 类型。鉴于您需要图像 mime 类型,您可以使用简单的 Python 字典来实现此目的。

不幸的是,我不知道 Python 中有任何方法试图通过读取一些魔法字节来猜测图像类型(就像fileinfo在 PHP 中所做的那样)。也许您可以将 EAFP(请求宽恕比许可更容易)原则与 Google appengine 图像 API 一起应用。

Yes, it appears that the image API does not tell you the type of image you've loaded. What I'd do in this case is to build that Python dictionary to map file extensions to image mime types and than try to load the image while expecting for a NotImageError() exception. If everything goes well, then I assume the mime type was OK.

于 2009-09-11T07:09:31.620 回答