我正在尝试使用python-magic包来识别上传的文件类型(使用 mime 类型),我用它来识别图像和音频文件,它工作正常,但对于视频文件,它会引发错误。
对于视频文件,我有
class VideoFileUploadForm(forms.ModelForm):
def clean(self):
cleaned_data = super(VideoFileUploadForm, self).clean()
upload_file = cleaned_data['upload']
try:
if upload_file:
supported_types = ['video/mp4', 'video/x-matroska',
'video/ogg','video/quicktime', 'video/x-ms-wmv',
'video/webm']
mimetype_of_file_uploaded = magic.from_buffer(upload_file.file.getvalue(), mime=True)
val = 0
for item1 in supported_types:
if item1 == mimetype_of_file_uploaded:
val = 1
break
if val == 0:
raise ValidationError(u'Error! File can only be .mp4, .mkv,.ogg,.mov ,.wmv and .webm(video) format')
except (RuntimeError, TypeError, NameError,AttributeError) as e:
print(e)
raise ValidationError("Error! Something is wrong.File should be .mp4,"
" .mkv,.ogg,.mov ,.wmv and .webm(video) format!")
class Meta:
model = VideoFileUpload
fields = (
'file_name',
'upload',
)
def __init__(self, *args, **kwargs):
super(VideoFileUploadForm, self).__init__(*args, **kwargs)
self.fields['upload'].widget.attrs = {
'class': 'btn btn-block',
'name': 'myCustomName',
'placeholder': 'Upload file',
'required': 'true'
}
如果我提供图像 mime 类型和音频 mime 类型来代替“supported_types”,则此代码可以正常工作,但现在对于视频,它不支持可能是什么原因
错误是这样的:'_io.BufferedRandom' 对象没有属性'getvalue'
我尝试上传的文件是 .mp4 格式,可以在媒体播放器中完美播放
或者,在上传之前有没有其他方法可以在 python/django 中验证 .mp4(video) 文件格式,这比这更好?