可能重复:
Django(音频)文件验证
我正在构建一个网络应用程序,用户可以在其中上传媒体内容,包括音频文件。
我的AudioFileUploadForm中有一个干净的方法可以验证以下内容:
- 音频文件不是太大。
- 音频文件具有有效的 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 文件的内容?