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?
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With