我正在尝试验证上传的文件。首先,我尝试检查扩展名。 但是如果带有以下扩展名的恶意文件也将通过检查。
def validate_file_extension(value):
ext = os.path.splitext(value.name)[1]
valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls', 'ppt']
if not ext.lower() in valid_extensions:
raise ValidationError(u'Unsupported file extension.')
然后我尝试使用python magic,它将查找文件并确定实际类型。
def validate_file_type(value):
file_type = magic.from_buffer(value.read(1024), mime=True)
valid_file_types = ['image/png',
'image/jpg','text/plain',
'application/pdf',
'application/ms-excel',]
if not file_type.lower() in valid_file_types:
raise ValidationError(u'Unsupported file.')
但是Excel,Word和ppt文件被识别为“应用程序/压缩文件”。因此不能将这种方法用于MS文档。 有没有更好的方法来验证上传文件?
答案 0 :(得分:0)
在这里找到了解决方案。 https://pypi.org/project/django-constrainedfilefield/
只需使用ConstrainedFileField
而不是FileField
。
这甚至可以验证文件扩展名是否已更改。
attach_file = ConstrainedFileField(
null=True,
blank=True,
upload_to='directory_path',
content_types=contents,
max_upload_size=1024000
)