Home Backend Development Python Tutorial Python determines upload file type

Python determines upload file type

Oct 17, 2016 pm 04:36 PM

When developing upload services, it is often necessary to filter uploaded files.

This article provides you with a python method to determine the file type through the file header, which is very practical.

The code is as follows

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('pythontab.jpg')
Copy after login

File headers of 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) D0CF11 E0

MS Access (mdb) 5374616E64617264204A


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles