drf base64转图片保存并验证图片是否能正常打开
最近在用drf做的一个前后台分离的项目,有个传图片的地方,前台想传base64
想了下决定在序列化器的校验器中做这个事
在此贴下序列化器代码
1 from rest_framework import serializers 2 from . import models 3 import base64 4 import os 5 import imghdr # 检验图片 6 from django.conf import settings 7 from utils.tools import get_order_code 8 9 class PaymentVoucherSerializer(serializers.ModelSerializer): 10 voucher_img = serializers.CharField() 11 12 def validate_voucher_img(self, voucher_img): 13 try: 14 imgdata = base64.b64decode(voucher_img) 15 filename = get_order_code() + '.jpg' 16 path = os.path.join(settings.MEDIA_ROOT, 'voucher_img') # 上传文件的保存路径 17 if not os.path.exists(path): 18 os.makedirs(path) 19 with open(path + '/' + filename, 'wb+')as f: 20 f.write(imgdata) 21 # 如果图片不完整,即无法正常打开时,res为None;正常时为图片类型 22 res = imghdr.what(path + '/' + filename) 23 if res: 24 voucher_img = settings.MEDIA_URL + 'voucher_img/' + filename 25 return voucher_img 26 except Exception as e: 27 log.error(e) 28 raise serializers.ValidationError("base64转换失败") 29 30 31 class Meta: 32 model = PaymentVoucher 33 exclude = ["addtime", "id"] 34 # fields = '__all__' 35 depth = 0
图片完整性检验参考:这里