我有一个允许用户上传图片的网站。要检查用户上传的文件的MIME类型,我使用以下使用python-magic
的脚本import magic
mime = magic.Magic(mime=True)
if mime.from_file(request.FILES['media-pic']) not in ['image/jpeg', 'image/pjpeg', 'image/png', 'image/gif']:
# don't allow the file to be uploaded
但是,当我尝试上传文件时,收到错误coercing to Unicode: need string or buffer, TemporaryUploadedFile found
。我认为它不会起作用,但我尝试request.FILES['media-pic'].name
并收到File does not exist
错误。
如何在文件的MIME类型保存到服务器之前检查它?
答案 0 :(得分:2)
mime.from_file
需要文件名,并且根据文件大小,上传的文件可能只存在于内存中。您可以使用mime.from_buffer
方法,使用以下内容:
f = request.FILES['media-pic']
# maybe even only read the first X bytes, might be enough for mimetype detection
mimetype = mime.from_buffer(f.read())