2014-07-09 120 views
7

我需要將一堆圖片導入到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 
+2

你試過把p = File(open('/ home/image001.png','r'))'改成'p = File(open('/ home/image001.png','rb 「))'? – MBrizzle

+0

我沒有,遺憾!這是問題所在。看起來,'r'和'rb'設置在Python 3中的工作方式與2中的不同 - http://stackoverflow.com/questions/9644110/difference-between-parsing-a-text-file-in-r-and -rb模式。 @MBrizzle - 如果你添加這個答案,我會接受。謝謝。 – Steve

+0

是的,'rb'標誌告訴文件句柄以二進制數據的形式讀取文件,這就是打開圖像,可執行文件等時要做的事情。 – Crispy

回答

16

我之前就已經這麼做了,所以我覺得你 - 但根據我的評論:在File()調用中將'r'替換爲'rb',它應該可以正常工作。

我還應該補充,對於那些後來發現這個答案的人來說,這是Python3特有的問題。看看史蒂夫評論中的SO鏈接,詳細解釋p2和p3之間File()的區別。

+0

工程就像一個魅力。謝謝,善良的先生或女士! – wastetime909