我正在尝试验证上传的文件。首先,我试着检查一下扩展。但如果带有以下扩展名的恶意文件也将通过检查。
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魔术,这将在文件中查找并决定实际的类型。
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文件被识别为“application/zip”。所以不能对MS文档使用这种方法。有没有更好的方法来验证上传的文件?
发布于 2019-03-08 16:28:52
在这里找到了一个解决方案。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
)https://stackoverflow.com/questions/55058752
复制相似问题