Django/Python:如何读取文件并验证它是音频文件? [复制]

2023-12-09

可能的重复:
Django(音频)文件验证

我正在构建一个网络应用程序,用户可以在其中上传媒体内容,包括音频文件。

我有一个干净的方法音频文件上传表单验证以下内容:

  • 音频文件不要太大。
  • 音频文件具有有效的 content_type(MIME 类型)。
  • 音频文件具有有效的扩展名。

不过我担心安全问题。用户可以上传带有恶意代码的文件,并轻松通过上述验证。接下来我想做的是验证音频文件确实是一个音频文件(在写入磁盘之前)。

我该怎么做?

class UploadAudioForm(forms.ModelForm):
    audio_file = forms.FileField()

    def clean_audio_file(self):
        file = self.cleaned_data.get('audio_file',False):
            if file:
                if file._size > 12*1024*1024:
                    raise ValidationError("Audio file too large ( > 12mb )")
                if not file.content_type in ['audio/mpeg','audio/mp4', 'audio/basic', 'audio/x-midi', 'audio/vorbis', 'audio/x-pn-realaudio', 'audio/vnd.rn-realaudio', 'audio/x-pn-realaudio', 'audio/vnd.rn-realaudio', 'audio/wav', 'audio/x-wav']:
                    raise ValidationError("Sorry, we do not support that audio MIME type. Please try uploading an mp3 file, or other common audio type.")
                if not os.path.splitext(file.name)[1] in ['.mp3', '.au', '.midi', '.ogg', '.ra', '.ram', '.wav']:
                    raise ValidationError("Sorry, your audio file doesn't have a proper extension.")
                # Next, I want to read the file and make sure it is 
                # a valid audio file. How should I do this? Use a library?
                # Read a portion of the file? ...?
                if not ???.is_audio(file.content):
                    raise ValidationError("Not a valid audio file.")
                return file
            else:
                raise ValidationError("Couldn't read uploaded file")

编辑:通过“验证音频文件确实是音频文件”,我的意思如下:

包含音频文件典型数据的文件。我担心用户可能会上传带有适当标头的文件,并用恶意脚本代替音频数据。例如... mp3 文件是mp3 文件吗?或者它是否包含 mp3 文件的非特征内容?


其他发布的答案的替代方案header解析。这意味着有人仍然可以在有效标头后面包含其他数据。

是验证整个文件,消耗更多的CPU,但也有更严格的策略。可以做到这一点的库是python 音频工具相关的API方法是音频文件.验证.

像这样使用:

import audiotools

f = audiotools.open(filename)
try:
    result = f.verify()
except audiotools.InvalidFile:
    # Invalid file.
    print("Invalid File")
else:
    # Valid file.
    print("Valid File")

A warning就是这个verify方法非常严格,实际上可以将编码错误的文件标记为无效。您必须自行决定这是否适合您的用例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django/Python:如何读取文件并验证它是音频文件? [复制] 的相关文章

随机推荐