python - 在 django 文件字段中保存 base64 图像

标签 python django image filefield

我有以下输入

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA7YAAAISCAIAAAB3YsSDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAA5JxJREFUeNrsnQl4FEX6xqcJJEAS7ivhBkMAQTSJ4h0QEQ+I90rAc1cOL3QBXXV1AV1dVwmrsCqQ9VwJ6HoC7oon0T8iEkABwRC5IeE+kkAIkPT/nfmSmprunskk5CDw/p55hu7qOr76api8........"

我想将此文件保存在文件字段中。我能做什么?

models.py

class SomeModel(models.Model):
    file = models.FileField(upload_to=get_upload_report)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

我正在尝试这样做

def get_file(data):
    from django.core.files import File
    return File(data)

并将返回文件保存到模型实例

somemodel.file = get_file(image_base64_data)

但它给出了以下错误

AttributeError at /someurl/

'File' object has no attribute 'decode'

最佳答案

import base64

from django.core.files.base import ContentFile
format, imgstr = data.split(';base64,') 
ext = format.split('/')[-1] 

data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) # You can save this as file instance.

使用此代码段解码 base64 字符串。

关于python - 在 django 文件字段中保存 base64 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39576174/

相关文章:

javascript - django post请求未在终端中显示javascript blob对象

django - 使用 celery 应用程序部署 Django 的最佳实践

image - 使用Nginx代理外部图像

python - 是否有使带有类型注释的 Python 3.5 代码向后兼容的策略?

python - 替换 pandas.datetime 列中的年份

python - Python中的Netcat实现

python - Django - 导入错误 : No module named apps

python - 如何将 Stellarium 生成的文件的二进制编码文件转换为 ASCII

image - 使用 FFMPEG 创建多个视频帧的单个图像

html - 无法将图像居中