3

I need to have the ability to upload files on the server but before uploading I would like to verify this file whether this file is and image or a script called image.jpeg. For this I'm using a library called python-magic

import magic

attachment = request.FILES['file'].read()
m = magic.open(magic.MAGIC_MIME_TYPE)
m.load()
ft = m.buffer(attachment)
m.close()

Its working fine for me. But should I read whole file?

 attachment = request.FILES['file'].read()

I think that this is a bad idea so my question is how much header of file weight? So than i can read only couple bytes and verify files mime-type.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
vovaminiof
  • 511
  • 1
  • 4
  • 13

1 Answers1

1

You could first guess the mimetype using the mimetype module as suggested here. If you are ok with the guess, upload the file to your webserver. In the case that you will access the file afterwards, you can do the entire check with the source you provided, as you have to read the file anyway.

Community
  • 1
  • 1
Thomas Kremmel
  • 14,575
  • 26
  • 108
  • 177