import filetype import os class MimeDetector: """文件MIME类型检测工具""" def __init__(self): pass def detect(self, file_path: str) -> str: """ 检测文件的MIME类型 Args: file_path: 文件路径 Returns: str: MIME类型字符串 """ try: # 使用filetype库检测文件类型 kind = filetype.guess(file_path) if kind: return kind.mime else: # 如果filetype无法检测,根据文件扩展名猜测 ext = os.path.splitext(file_path)[1].lower() ext_to_mime = { '.txt': 'text/plain', '.md': 'text/markdown', '.pdf': 'application/pdf', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.doc': 'application/msword', '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.xls': 'application/vnd.ms-excel', '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', '.ppt': 'application/vnd.ms-powerpoint', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.mp4': 'video/mp4', '.avi': 'video/x-msvideo', '.mov': 'video/quicktime' } return ext_to_mime.get(ext, 'application/octet-stream') except Exception as e: raise Exception(f"文件类型检测失败: {str(e)}")