在django文件字段中保存base64图像 [英] Save base64 image in django file field

查看:2164
本文介绍了在django文件字段中保存base64图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下输入

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

我想将此文件保存在文件字段中。我该怎么办?

I want to save this file in file field. What can I do?

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)

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

and save return file to model instance

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字符串。

Use this code snippet to decode the base64 string.

这篇关于在django文件字段中保存base64图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆