首页 > 解决方案 > UnicodeDecodeError:尝试将图像保存到 django 模型时

问题描述

我有这个模型:

class MyModel(Model):

    other_field = CharField(max_length=200)
    image = ImageField(upload_to='images/', null=True, blank=True, )

我进入外壳

Python manage.py shell

然后:

import os
from django.core.files import File

my_image1_path = 'C:\\Users\\Amin\\PycharmProjects\\myproject\\myimage1.png'
my_image1_file = File(open(my_image1_path ))
from myapp.models import MyModel
model_ins = MyModel.objects.get(id=1)
model_ins.image.save('myimage1.png', my_image1_file )

我遇到这个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

我的模型中有另一个 ins 并且我没有遇到其他图像文件的错误:

import os
from django.core.files import File

import os
from django.core.files import File

my_image1_path = 'C:\\Users\\Amin\\PycharmProjects\\myproject\\myimage2.svg'
my_image1_file = File(open(my_image2_path ))
from myapp.models import MyModel
model_ins = MyModel.objects.get(id=2)
model_ins.image.save('myimage2.svg', my_image2_file ) 

任何线索 image1 有什么问题?!

标签: pythondjangoimagemodel

解决方案


问题是open默认情况下将文件作为文本打开,而不是二进制流。

因此,您可以通过将模式设置为来打开它'rb'

with open(my_image1_path, 'rb') as f:
    my_image1_file = File(f)

使用上下文管理器(with块),以确保正确关闭文件。


推荐阅读