在Django中把Base64字符串保存为ImageField

在数据model中使用ImageField来管理avatar。

python 复制代码
class User(models.Model):
    AVATAR_COLORS = (
        ('#212736', 'Black'),
        ('#2161FD', 'Blue'),
        ('#36B37E', 'Green'),
        ('#F5121D', 'Red'),
        ('#FE802F', 'Orange'),
        ('#9254DE', 'Purple'),
        ('#EB2F96', 'Magenta'),
    )

    def generate_filename(self, filename):
        url = "avatar-{}-{}".format(self.user.username, filename)
        return url
    avatar = models.ImageField(upload_to=generate_filename, verbose_name='头像', null=True, blank=True)
    avatar_color = models.CharField(verbose_name='头像颜色', choices=AVATAR_COLORS, max_length=10, blank=True, null=True)
    #这里省略其他字段

前端avatar字段传输的是Base64字符串,Django后端将其转换为ContentFile后进行save。

首先,确保你已经安装了Pillow库,它是Django中处理图像的常用库。

python 复制代码
import base64
import binascii
import imghdr
import io
import uuid

from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile


class Base64ToImageFile(object):
    """
    A django-rest-framework field for handling image-uploads through raw post data.
    It uses base64 for en-/decoding the contents of the file.
    """
    ALLOWED_TYPES = (
        "jpeg",
        "jpg",
        "png",
        "gif"
    )
    EMPTY_VALUES = (None, '', [], (), {})
    INVALID_FILE_MESSAGE = "Please upload a valid image."
    INVALID_TYPE_MESSAGE = "The type of the image couldn't be determined."

    def to_file(self, base64_data):
        # Check if this is a base64 string
        if base64_data in self.EMPTY_VALUES:
            return None
        if isinstance(base64_data, str):
            # Strip base64 header.
            if ';base64,' in base64_data:
                header, base64_data = base64_data.split(';base64,')

            # Try to decode the file. Return validation error if it fails.
            try:
                decoded_file = base64.b64decode(base64_data)
            except (TypeError, binascii.Error, ValueError):
                raise ValidationError(self.INVALID_FILE_MESSAGE)
            # Generate file name:
            file_name = self.get_file_name(decoded_file)
            # Get the file name extension:
            file_extension = self.get_file_extension(file_name, decoded_file)
            if file_extension not in self.ALLOWED_TYPES:
                raise ValidationError(self.INVALID_TYPE_MESSAGE)
            complete_file_name = file_name + "." + file_extension
            data = ContentFile(decoded_file, name=complete_file_name)
            return data
        raise ValidationError('Invalid type. This is not an base64 string: {}'.format(
            type(base64_data)))

    def get_file_name(self, decoded_file):
        return str(uuid.uuid4())

    def get_file_extension(self, filename, decoded_file):
        try:
            from PIL import Image
        except ImportError:
            raise ImportError("Pillow is not installed.")
        extension = imghdr.what(filename, decoded_file)

        # Try with PIL as fallback if format not detected due
        # to bug in imghdr https://bugs.python.org/issue16512
        if extension is None:
            try:
                image = Image.open(io.BytesIO(decoded_file))
            except (OSError, IOError):
                raise ValidationError(self.INVALID_FILE_MESSAGE)

            extension = image.format.lower()

        extension = "jpg" if extension == "jpeg" else extension
        return extension


def base64_string_to_file(base64_string):
    return Base64ToImageFile().to_file(base64_string)

在创建用户过程中,给avatar字段赋值ContentFile类型

python 复制代码
        avatar_file = base64_string_to_file(avatar_string)
        if avatar_file:
            request_data["avatar"] = avatar_file
        else:
            request_data.pop('avatar', None)
        serializer = UserCreateSerializer(data=request_data)
        if serializer.is_valid():
            user = serializer.save()
相关推荐
小马哥编程8 分钟前
【软考架构】第6章 数据库基本概念
数据库·oracle·架构
自学也学好编程9 分钟前
【数据库】PostgreSQL详解:企业级关系型数据库
数据库·postgresql
.Eyes1 小时前
OceanBase 分区裁剪(Partition Pruning)原理解读
数据库·oceanbase
MrZhangBaby2 小时前
SQL-leetcode— 2356. 每位教师所教授的科目种类的数量
数据库
一水鉴天3 小时前
整体设计 之定稿 “凝聚式中心点”原型 --整除:智能合约和DBMS的在表层挂接 能/所 依据的深层套接 之2
数据库·人工智能·智能合约
翔云1234563 小时前
Python 中 SQLAlchemy 和 MySQLdb 的关系
数据库·python·mysql
孙霸天3 小时前
Ubuntu20系统上离线安装MongoDB
数据库·mongodb·ubuntu·备份还原
Java 码农3 小时前
nodejs mongodb基础
数据库·mongodb·node.js
TDengine (老段)4 小时前
TDengine IDMP 运维指南(4. 使用 Docker 部署)
运维·数据库·物联网·docker·时序数据库·tdengine·涛思数据
TDengine (老段)4 小时前
TDengine IDMP 最佳实践
大数据·数据库·物联网·ai·时序数据库·tdengine·涛思数据