For the server that provides the upload, the uploaded file needs to be filtered.
This article provides a way for Python to determine file types through the file header, avoiding unnecessary hassles.
Share the code below
Import struct # support file type # with 16 binary string is the purpose is to know the file header is how many bytes # various file header length is not the same, less half 2 characters long 8 characters def typelist (): return { " 52617221 ": Ext_rar, " 504b0304 ": Ext_zip} # Bytecode to 16 binary string def bytes2hex (bytes): num = len (bytes) hexstr = U "" for I in range (num): t = u "%x"% bytes[i] if Len (t)% 2: hexstr + = u "0" hexstr + = t return Hexstr.upper () # Gets the file type def filetype (filename): binfile = open (filename, ' RB ') # required binary word read TL = typelist () C16/>ftype = ' unknown ' for Hcode in Tl.keys (): numofbytes = Len (hcode)/2 # required to read how many bytes binfile.seek (0) # per read Go back to the file header, or you'll read it backwards. hbytes = Struct.unpack_from ("b" *numofbytes, Binfile.read (numofbytes)) # a "B" means one byte f_ Hcode = Bytes2hex (hbytes) if F_hcode = = Hcode: ftype = Tl[hcode] Break binfile.close () Return ftype If __name__ = = ' __main__ ': print filetype (your-file-path)
File headers for common file formats
file Format file header (hex)
JPEG (jpg)Ffd8ff
PNG (PNG)89504E47
gif (GIF)47494638
TIFF (TIF)49492a00
Windows Bitmap (BMP)424D
CAD (DWG)41433130
Adobe Photoshop (PSD)38425053
Rich Text Format (RTF)7b5c727466
XML (XML)3c3f786d6c
HTML (HTML)68746d6c3e
Email [Thorough only] (EML)44656c69766572792d646174653a
Outlook Express (dbx)cfad12fec5fd746f
Outlook (PST)2142444E
MS word/excel (xls.or.doc)D0cf11e0
MS Access (MDB)5374616e64617264204a
The above is the whole content of this article, I hope that everyone's study has helped.