黑松山资源网 Design By www.paidiu.com
对于提供上传的服务器,需要对上传的文件进行过滤。
本文为大家提供了python通过文件头判断文件类型的方法,避免不必要的麻烦。
分享代码如下
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
以上就是本文的全部内容,希望对大家的学习有所帮助。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- 徐璨宾《井底的蚯蚓》[320K/MP3][78.77MB]
- 碧蓝航线国庆金秋版本重磅上线 新玩法3D宿舍系统闪亮登场
- 自在西游自在服即将在10月1日开启 入驻即享豪礼满满
- 炉石传说最强术士卡组是哪个 术士最强天梯卡组推荐一览
- 炉石传说最强萨尔卡组是哪个 萨尔最强天梯卡组推荐一览
- 炉石传说最强潜行者卡组是哪个 潜行者最强天梯卡组推荐一览
- 银霞.1983-《爱迷惑我·我住小楼中》台湾复刻版[WAV+CUE]
- [雨果唱片]粤曲名家-《再折长亭柳》[WAV+CUE]
- 刘德华1998-你是我的女人[香港第二版][WAV]
- 压迫感谁最强?外媒评选恐怖游戏最佳女反派
- 还没正式发售:《寂静岭2:重制版》Steam玩家峰值近9000人
- 别搞政确了!超95%国外玩家反对强制包容性
- 《暗喻幻想:ReFantazio》试玩:ATLUS的自我挑战?
- 《憧憬成为魔法少女》第二季 反转魔法少女题材再掀热潮
- 海信AI电视E7N正式发布,引领AI画质新标杆