gpt4 book ai didi

python - 判断base64上传的文件扩展名和mime类型

转载 作者:行者123 更新时间:2023-12-02 22:36:58 25 4
gpt4 key购买 nike

我有一个用于上传 base64 音频的 FileField 序列化程序,我注意到 Base64 字符串不是以 data:**** 开头。如何确定上传文件的 Mime 类型? i_need_the_file_extension_mimetype()

class AudioField(serializers.FileField):
def to_internal_value(self, data):
if isinstance(data, basestring):
data = re.sub(r"^data\:.+base64\,(.+)$", r"\1", data)

# Try to base64 decode the data url.
try:
decoded = base64.b64decode(data)
except TypeError:
raise serializers.ValidationError(_('Not a valid file'))

file_name, file_ext, mime_type = self.i_need_the_file_extension_mimetype(decoded)


data = ContentFile(decoded, name=file_name)

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

最佳答案

我终于用 python-magic 解决了这个问题感谢@Ralf 的指点

class AudioField(serializers.FileField):
def to_internal_value(self, data):
# Check to see if it's a base64 encoded file.
if isinstance(data, basestring):
# Strip out the data header if it exists.
data = re.sub(r"^data\:.+base64\,(.+)$", r"\1", data)

try:
decoded = base64.b64decode(data)
mime_type = magic.from_buffer(decoded, mime=True)
file_ext = mimetypes.guess_extension(mime_type)

except TypeError:
raise serializers.ValidationError(_('Not a valid file'))

file_name = "{}{}".format(uuid.uuid4(), file_ext)

# Check if it's a valid file extension.
if file_ext[1:] not in settings.VOICE_VALID_FILE_EXTENSIONS:
raise serializers.ValidationError(_('Invalid file type.'))

# Update the data dict with new values.
data = ContentFile(decoded, name=file_name)

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

必需:pip install python-magic

关于python - 判断base64上传的文件扩展名和mime类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49910137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com