当前位置: 首页 > news >正文

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

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

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 urlavatar = 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中处理图像的常用库。

import base64
import binascii
import imghdr
import io
import uuidfrom django.core.exceptions import ValidationError
from django.core.files.base import ContentFileclass 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 stringif base64_data in self.EMPTY_VALUES:return Noneif 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_extensiondata = ContentFile(decoded_file, name=complete_file_name)return dataraise 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 Imageexcept 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/issue16512if 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 extensionreturn extensiondef base64_string_to_file(base64_string):return Base64ToImageFile().to_file(base64_string)

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

        avatar_file = base64_string_to_file(avatar_string)if avatar_file:request_data["avatar"] = avatar_fileelse:request_data.pop('avatar', None)serializer = UserCreateSerializer(data=request_data)if serializer.is_valid():user = serializer.save()

http://www.lqws.cn/news/452881.html

相关文章:

  • 思辨场域丨AR技术如何重塑未来学术会议体验?
  • LVS vs Nginx 负载均衡对比:全面解析
  • leetcode-2966.划分数组并满足最大差限制
  • 多相机三维人脸扫描仪:超写实数字人模型制作“加速器”
  • Android Java语言转Kotlin语言学习指导实用攻略
  • 单片机3种按键程序消抖方法
  • DB-GPT启动提示please install by running `pip install cryptography`
  • 函数指针的回调函数与函数跳转执行
  • 国产芯片能在服务器领域替代Intel(经验总结贴)
  • Git——分布式版本控制工具
  • 【MySQL篇07】:redo log日志与buffer pool详解
  • Vue2 ElementUI Tree 拖动目标节点能否被放置及获取放置位置
  • 内存的代价:如何正确与 WASM 模块传值交互
  • 大内存对电脑性能有哪些提升
  • Docker容器常用命令汇总
  • 游戏架构中的第三方SDK集成艺术:构建安全高效的接入体系
  • 16、Redis底层数据结构
  • 网站如何启用HTTPS访问?本地内网部署的https网站怎么在外网打开?
  • FPGA--hello
  • http通信测试,模拟客户端
  • 【动手学深度学习】4.5. 权重衰减
  • Hollywood: The World’s Most Effective Propaganda System
  • 【云创智城】YunCharge充电桩系统源码实现云快充协议深度解析与Java技术实践:打造高效充电桩运营系统
  • Selenium自动化测试全解
  • opencv依据图像类型读取图像像素点
  • 【PyTorch】请问,Reproducibility中的‘:4096:8‘是什么呀?
  • 20250620-Pandas.cut
  • aws(学习笔记第四十五课) route53-failover
  • 文件夹美化工具推荐,打造个性化电脑界面
  • 【网工】华为配置专题进阶篇④