【发布时间】:2014-08-31 03:53:49
【问题描述】:
我需要将一堆图像导入 Django 应用程序。我正在 shell 中进行测试,但在尝试保存图像时无法克服此错误:
File "/lib/python3.3/codecs.py", line 301, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0:
invalid start byte
型号:
import uuid
from django.db import models
from taggit.managers import TaggableManager
import os
def generate_filename(instance, filename):
f, ext = os.path.splitext(filename)
name = uuid.uuid4().hex
return 'images/%s%s' % (name, ext)
class StudyImage(models.Model):
pic = models.ImageField(upload_to=generate_filename)
upload_date = models.DateTimeField(auto_now_add=True)
tags = TaggableManager()
解决错误的步骤:
打开一个 django shell。
import uuid
import os
from app import models
p = File(open('/home/image001.png', 'r'))
a = models.StudyImage(pic=p)
a.pic.save('test.jpg',p)
这给出了上面的错误。我无法弄清楚为什么图像会出现 unicodecodeerror ......我到此为止指的是"Upload" a file from django shell
更多细节:
Django 1.7、Python 3.3
完整的追溯:
Traceback (most recent call last):<br>
File "<input>", line 1, in <module><br>
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-
packages/django/db/models/fields/files.py", line 89, in save
self.name = self.storage.save(name, content)
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-
packages/django/core/files/storage.py", line 51, in save
name = self._save(name, content)
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-
packages/django/core/files/storage.py", line 224, in _save
for chunk in content.chunks():
File "/home/s/Pycharm/flf/venv/lib/python3.3/site-packages/django/core/files/base.py",
line 77, in chunks
data = self.read(chunk_size)
File "/home/s/Pycharm/flf/venv/lib/python3.3/codecs.py", line 301, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
【问题讨论】:
-
你试过把
p = File(open('/home/image001.png', 'r'))换成p = File(open('/home/image001.png', 'rb'))吗? -
我没有,很遗憾!这就是问题所在。似乎 'r' 和 'rb' 设置在 Python 3 中的工作方式与在 2 - stackoverflow.com/questions/9644110/… 中不同。 @MBrizzle - 如果您将此添加为我会接受的答案。谢谢。
-
是的,
rb标志告诉文件句柄将文件作为二进制数据读取,这是您在打开图像、可执行文件等时会执行的操作。