Only accept a certain file type in FileField, server-side

前端 未结 10 657
日久生厌
日久生厌 2020-11-27 02:56

How can I restrict FileField to only accept a certain type of file (video, audio, pdf, etc.) in an elegant way, server-side?

10条回答
  •  庸人自扰
    2020-11-27 03:23

    Django in version 1.11 has a newly added FileExtensionValidator for model fields, the docs is here: https://docs.djangoproject.com/en/dev/ref/validators/#fileextensionvalidator.

    An example of how to validate a file extension:

    from django.core.validators import FileExtensionValidator
    from django.db import models
    
    class MyModel(models.Model):
        pdf_file = models.FileField(upload_to='foo/',
                                    validators=[FileExtensionValidator(allowed_extensions=['pdf'])])
    

    Note that this method is not safe. Citation from Django docs:

    Don’t rely on validation of the file extension to determine a file’s type. Files can be renamed to have any extension no matter what data they contain.

    There is also new validate_image_file_extension (https://docs.djangoproject.com/en/dev/ref/validators/#validate-image-file-extension) for validating image extensions (using Pillow).

提交回复
热议问题