Reputation: 392
I'm creating a Rest API with Django Rest Framework, and in some call, I need upload one of different file types.
For do this, I am using drf-extra-fields and I have this problem:
When the client convert file to Base64, the filename change and lose the file extension, for suply this, I created in serializer, new CharField called "file_extension":
class MySerializer(serializers.ModelSerializer):
# Some other fields...
file = FileField(required=False)
file_extension = serializers.CharField(required=False)
class Meta:
# model and fields...
I created my custom Base64FileField, and set some allowed types and my method for get file extension:
class FileField(Base64FileField):
ALLOWED_TYPES = ['pdf', 'txt', 'xml']
def get_file_extension(self, filename, decoded_file):
# Not working because the filename not include extension.
return filename.split('.')[-1]
For solve this, I thinked set filename in serializer with file extension (taked for the other field) before get_file_extension is called.
Thanks you!
Upvotes: 1
Views: 1681
Reputation: 25
Use filetype to identify the type of the decoded_file
import filetype
class FileField(Base64FileField):
ALLOWED_TYPES = ['pdf', 'txt', 'xml']
def get_file_extension(self, filename, decoded_file):
kind = filetype.guess(decoded_file)
return kind.extension
Upvotes: 1