對于提供上傳的服務器,需要對上傳的文件進行過濾。
本文為大家提供了python通過文件頭判斷文件類型的方法,避免不必要的麻煩。
分享代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import struct # 支持文件類型 # 用16進制字符串的目的是可以知道文件頭是多少字節 # 各種文件頭的長度不一樣,少半2字符,長則8字符 def typeList(): return { "52617221" : EXT_RAR, "504B0304" : EXT_ZIP} # 字節碼轉16進制字符串 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() # 獲取文件類型 def filetype(filename): binfile = open (filename, 'rb' ) # 必需二制字讀取 tl = typeList() ftype = 'unknown' for hcode in tl.keys(): numOfBytes = len (hcode) / 2 # 需要讀多少字節 binfile.seek( 0 ) # 每次讀取都要回到文件頭,不然會一直往后讀取 hbytes = struct.unpack_from( "B" * numOfBytes, binfile.read(numOfBytes)) # 一個 "B"表示一個字節 f_hcode = bytes2hex(hbytes) if f_hcode = = hcode: ftype = tl[hcode] break binfile.close() return ftype if __name__ = = '__main__' : print filetype(Your - file - path) |
常見文件格式的文件頭
文件格式 文件頭(十六進制)
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
以上就是本文的全部內容,希望對大家的學習有所幫助。