Django - 上传文件类型验证

Bab*_*abu 5 python validation file-upload file-type django-forms

我需要验证上传文件的文件类型,并且只允许pdf,普通测试和MS word文件.这是我的模型和带验证功能的表单.但是,即使没有扩展名,我也可以上传文件.

class Section(models.Model):
    content = models.FileField(upload_to="documents")

class SectionForm(forms.ModelForm):
    class Meta:
        model = Section
    FILE_EXT_WHITELIST = ['pdf','text','msword']

    def clean_content(self):
        content = self.cleaned_data['content']
        if content:
            file_type = content.content_type.split('/')[0]
            print file_type
            if len(content.name.split('.')) == 1:
                raise forms.ValidationError("File type is not supported.")
            if content.name.split('.')[-1] in self.FILE_EXT_WHITELIST:
                return content
            else:
                raise forms.ValidationError("Only '.txt' and '.pdf' files are allowed.")
Run Code Online (Sandbox Code Playgroud)

这是视图,

def section_update(request, object_id):
    section = models.Section.objects.get(pk=object_id)
    if 'content' in request.FILES:
            if request.FILES['content'].name.split('.')[-1] == "pdf":
                content_file = ContentFile(request.FILES['content'].read())
                content_type = "pdf"
                section.content.save("test"+'.'+content_type , content_file)
                section.save()
Run Code Online (Sandbox Code Playgroud)

在我看来,我只是保存文件request.FILE.我想虽然save()它会调用clean_content并进行内容类型验证.我想,clean_content根本不需要验证.

Aar*_*lla 5

你的方法不起作用:作为一个攻击者,我可以简单地伪造HTML标题,向你发送任何mime类型的东西text/plain.

正确的解决方案是使用像file(1)Unix上的工具来检查文件的内容以确定它是什么.请注意,没有什么好方法可以知道某些内容是否真的是纯文本.如果文件以16位Unicode保存,则"纯文本"甚至可以包含0个字节.

有关如何执行此操作的选项,请参阅此问题:如何在python中查找文件的mime类型?