将StringIO对象转换为Django ImageFile

7 投票
1 回答
6836 浏览
提问于 2025-04-16 15:13

我正在尝试从一个StringIO(更具体来说是cStringIO)中获取数据,并把它转换成django.core.files.images.ImageFile。

但是这并不成功。具体来说,它有很多种失败的方式,而我在网上搜索也没有找到解决办法。

到目前为止,我得到了:

pi = ProductImage(product=product)
image = ImageFile(image_file)
image.name = image_name # defined elsewhere
pi.source_image.save(image_name, image)
pi.save()

我的错误信息大致是这样的:

File "dev.py", line 359, in process_csv_item
  pi.source_image.save(image_name, image)
File "C:\Python26\lib\site-packages\django\db\models\fields\files.py", line 92, in save
  self.name = self.storage.save(name, content)
File "C:\Python26\lib\site-packages\django\core\files\storage.py", line 48, in save
  name = self._save(name, content)
File "C:\Python26\lib\site-packages\django\core\files\storage.py", line 168, in _save
  for chunk in content.chunks():
File "C:\Python26\lib\site-packages\django\core\files\base.py", line 65, in chunks
  counter = self.size
File "C:\Python26\lib\site-packages\django\core\files\base.py", line 39, in _get_size
  elif os.path.exists(self.file.name):
AttributeError: 'cStringIO.StringI' object has no attribute 'name'

接下来我该去哪里找解决方案呢?

1 个回答

16

使用 django.core.files.base.ContentFile(image_file) 这个方法:

pi = ProductImage(product=product)
pi.source_image.save(image_name, ContentFile(image_file.read()))
pi.save()

撰写回答