我需要將一堆圖片導入到Django應用程序中。我在shell測試,但嘗試保存圖像時不能讓過去這個錯誤: 從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殼。
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 「))'? – MBrizzle
我沒有,遺憾!這是問題所在。看起來,'r'和'rb'設置在Python 3中的工作方式與2中的不同 - http://stackoverflow.com/questions/9644110/difference-between-parsing-a-text-file-in-r-and -rb模式。 @MBrizzle - 如果你添加這個答案,我會接受。謝謝。 – Steve
是的,'rb'標誌告訴文件句柄以二進制數據的形式讀取文件,這就是打開圖像,可執行文件等時要做的事情。 – Crispy