" IOError:无法识别图像文件"同时将文件内容保存到Django中的ImageField

时间:2016-03-11 09:12:05

标签: python django sorl-thumbnail imagefield

如何在Django中将生成的文件内容保存到ImageField? 我目前的代码是:

from django.contrib.contenttypes.models import ContentType

image = create_screenshot(url)
print type(image) # <type 'str'>
screenshot = ScreenshotModel(...)
screenshot.image.save('filename.jpg', ContentFile(image), save=True)

这会在保存时产生没有错误,但在尝试显示图片时会出错(使用sorl.thumbnail):

IOError: cannot identify image file <cStringIO.StringI object at 0x7fda5322c140>

文件正在正确保存在磁盘上,但它不是图像,我无法显示它。我检查了文件mime类型,它是application/octet-stream

函数create_screenshot使用PhantomJS生成图像并返回phantomjs脚本的原始输出 - 当我使用它生成PDF文档并将其保存到FileField时一切正常。

0 个答案:

没有答案