Django Rest Framework-如何使用序列化器将图像导入为JPEG并将其保存为base 64?

时间:2019-02-12 11:10:35

标签: python django django-models django-rest-framework

型号:

class Item(models.Model):

   class Meta:
       db_table = 't_item'

   item_name = models.CharField(max_length=200)
   image = models.ImageField(upload_to='item_images')
   created_at = models.DateTimeField(default=datetime.now, blank=True)
   updated_at = models.DateTimeField(default=datetime.now, blank=True)

   def __str__(self):
       return self.item_name

序列化器:

class ItemSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Item
        # Fields you want to be returned or posted
        fields = ('item_name', 'image', 'created_at', 'updated_at')

在Web视图表单中,我想导入JPEG格式的图像,并在发布后将其保存为Base 64格式,位于“ upload_to”中指定的位置。这可能吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试

在serailizer.py

class Base64ImageField(serializers.ImageField):

    def to_internal_value(self, data):

        from django.core.files.base import ContentFile
        import base64
        import six
        import uuid

        # Check if this is a base64 string
        if isinstance(data, six.string_types):
            # Check if the base64 string is in the "data:" format
            if 'data:' in data and ';base64,' in data:
                # Break out the header from the base64 content
                header, data = data.split(';base64,')

            # Try to decode the file. Return validation error if it fails.
            try:
                decoded_file = base64.b64decode(data)
            except TypeError:
                self.fail('invalid_image')

            # Generate file name:
            file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
            # Get the file name extension:
            file_extension = self.get_file_extension(file_name, decoded_file)

            complete_file_name = "%s.%s" % (file_name, file_extension, )

            data = ContentFile(decoded_file, name=complete_file_name)

        return super(Base64ImageField, self).to_internal_value(data)

    def get_file_extension(self, file_name, decoded_file):
        import imghdr
        extension = imghdr.what(file_name, decoded_file)
        extension = "jpg" if extension == "jpeg" else extension

        return extension

class ItemSerializer(serializers.ModelSerializer):
   image = Base64ImageField(required=True)

在您的api视图中

class ImageSave(APIView):
   serializer_class = ItemSerializer
   def post(self):
      serializer_instance = 
      self.serializer_class(data=self.request.data)

      if serializer_instance.is_valid():
         serializer_instance.save()

      return Response({})

希望有帮助

答案 1 :(得分:0)

  

编写模型的保存功能并访问那里的上传图像   然后将其编码为base64并保存到不可编辑的base64Image字段中。

6k2