将解码的临时图像保存到Django Imagefield [英] Saving a decoded temporary image to Django Imagefield

查看:97
本文介绍了将解码的临时图像保存到Django Imagefield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将已经作为Base64编码文本传递给我的图像保存到Django Imagefield中。

I'm trying to save images which have been passed to me as Base64 encoded text into a Django Imagefield.

但是似乎没有正确保存。数据库报告我的所有图像都以的形式存储为文件名,例如:

But it seems to not be saving correctly. The database reports all my images are stored as "" when it should report them as a filename for example:

"template_images/template_folders/myImage.png"

正在尝试保存图像的代码如下:

The code that's trying to save my images is as follows:

elif model_field.get_internal_type() == "ImageField" or model_field.get_internal_type() == "FileField":  # Convert files from base64 back to a file.
    if field_elt.text is not None:
        setattr(instance, model_field.name, File(b64decode(field_elt.text)))


推荐答案

阅读这个答案,我得到了这个工作:

After reading this answer, I got this to work:

from base64 import b64decode
from django.core.files.base import ContentFile

image_data = b64decode(b64_text)
my_model_instance.cool_image_field = ContentFile(image_data, 'whatup.png')
my_model_instance.save()

因此,我建议您更改代码到:

Therefore, I suggest you change your code to:

from django.core.files.base import ContentFile

# Your other code...

elif model_field.get_internal_type() == "ImageField" or model_field.get_internal_type() == "FileField":  # Convert files from base64 back to a file.
    if field_elt.text is not None:
        image_data = b64decode(field_elt.text)
        setattr(instance, model_field.name, ContentFile(image_data, 'myImage.png'))

然后,假设您的 ImageField 被定义为 upload_to 参数设置为 template_images / template_folders / ,您应该会看到文件保存到 YOUR_MEDIA_URL / template_images /template_folders/myImage.png

Then, assuming your ImageField is defined with the upload_to argument set to template_images/template_folders/, you should see the file save down to YOUR_MEDIA_URL/template_images/template_folders/myImage.png

这篇关于将解码的临时图像保存到Django Imagefield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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