python - 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 有什么问题?!
解决方案
问题是open
默认情况下将文件作为文本打开,而不是二进制流。
因此,您可以通过将模式设置为来打开它'rb'
:
with open(my_image1_path, 'rb') as f:
my_image1_file = File(f)
使用上下文管理器(with
块),以确保正确关闭文件。
推荐阅读
- selenium - 单击机器人框架中动态填充的地址
- konvajs - 错误类型错误:context._applyGlobalCompositeOperation 不是 Konva js 中的函数
- java - POI HSSF 未迭代完整的行集
- swift - 更改对象的框架大小后更新自动布局
- sql - 如何将两个不同的表与不同的列组合起来
- android - 遍历从 alertController 返回的数据
- python - 如何正确绘制超大刻度?
- javascript - 如何使用 JavaScript 解析 JSON 格式的数据?
- asp.net-core - Entity Framework Core 存储来自多个数据源的多对多关系
- asp.net-mvc - 将 Web 应用程序 (MVC) 发布到 Azure(蓝屏)