0
votes

I created an application where I can store images of products. In the database I store just directions to images which are held in designated folder. In my serializer I need to validate the files names and check if the extensions are photo extensions. I wrote something like this below, is it the best way to checking it? Is there maybe more safe method?

ALLOWED_IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "bmp", "gif"]


class ProductImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductImage
        fields = [...]


class ProductSerializer(serializers.ModelSerializer):
    images = ProductImageSerializer(many=True, read_only=True)

    class Meta:
        model = Product
        fields = [..., 'images']

    def create(self, validated_data):
        ...

        for file in self.context['request'].FILES.getlist('images'):
            validate_extension(file.name)
            ...

        return item


def validate_extension(filename):
    extension = os.path.splitext(filename)[1].replace(".", "")
    if extension.lower() not in ALLOWED_IMAGE_EXTENSIONS:
        raise serializers.ValidationError(
            (f'Invalid uploaded file type: {filename}'),
            code='invalid',
        )
1

1 Answers

0
votes

You could add 2 further checks. Firstly, you could validate the mime type of the file e.g. using the python-magic package in linux (python-magic-bin for windows). Also, you could compare the file size with the desired max file size in your project.