【问题标题】:How to transfer images to Django REST framework applications?如何将图像传输到 Django REST 框架应用程序?
【发布时间】:2019-12-23 18:20:19
【问题描述】:
我已经了解了一些关于 REST API 的知识,现在在学习的同时,作为一种实践,我正在尝试使用 Python Django 的 REST 框架构建一个。我面临的困难是,我无法从 POSTMAN 或 Curl 或任何其他 REST 客户端发出包含图像的 POST 请求。我看到图像可以编码成base64然后传输。不幸的是,互联网资源对我的帮助不足以让我自己做。现在任何人都可以帮助我并走出整个过程以使其更容易吗?
提前致谢。
【问题讨论】:
标签:
python
django
image
django-rest-framework
base64
【解决方案1】:
您可以像这样自定义django rest框架(DRF)的ImageField:
class Base64ImageField(serializers.ImageField):
"""
A Django REST framework field for handling image-uploads through raw post data.
It uses base64 for encoding and decoding the contents of the file. """
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 Exception:
raise serializers.ValidationError(_('Invalid image format'))
file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
# Get the file name extension:
file_extension = self.get_file_extension(header)
complete_file_name = "%s.%s" % (file_name, file_extension,)
data = ContentFile(decoded_file, name=complete_file_name)
else:
raise serializers.ValidationError(_('Invalid image format'))
return super(Base64ImageField, self).to_internal_value(data)
def get_file_extension(self, header):
data, format = header.split('/')
return format
并在您的ModelSerializer 中像这样使用它:
class AddImageSerializer(serializers.ModelSerializer):
image = Base64ImageField(use_url=True)
class Meta:
model = YourModel
fields = ('image',)