Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check mime type of uploaded file in Django

I have a website that allows users to upload images. To check the MIME type of the file the user uploaded I am using the following script that uses 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

However, when I try to upload a file, I get the error coercing to Unicode: need string or buffer, TemporaryUploadedFile found. I didn't think it would work, but I tried request.FILES['media-pic'].name and got a File does not exist error.

How do I check the MIME type of the file before it has been saved on the server?

like image 298
Hat Avatar asked Sep 11 '25 22:09

Hat


1 Answers

mime.from_file expects a file name, and depending on the file size, the uploaded file might exist only in memory. You can instead use the mime.from_buffer method, using something like this:

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())
like image 181
sk1p Avatar answered Sep 13 '25 20:09

sk1p