mime_detector.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import filetype
  2. import os
  3. class MimeDetector:
  4. """文件MIME类型检测工具"""
  5. def __init__(self):
  6. pass
  7. def detect(self, file_path: str) -> str:
  8. """
  9. 检测文件的MIME类型
  10. Args:
  11. file_path: 文件路径
  12. Returns:
  13. str: MIME类型字符串
  14. """
  15. try:
  16. # 使用filetype库检测文件类型
  17. kind = filetype.guess(file_path)
  18. if kind:
  19. return kind.mime
  20. else:
  21. # 如果filetype无法检测,根据文件扩展名猜测
  22. ext = os.path.splitext(file_path)[1].lower()
  23. ext_to_mime = {
  24. '.txt': 'text/plain',
  25. '.md': 'text/markdown',
  26. '.pdf': 'application/pdf',
  27. '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  28. '.doc': 'application/msword',
  29. '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  30. '.xls': 'application/vnd.ms-excel',
  31. '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  32. '.ppt': 'application/vnd.ms-powerpoint',
  33. '.jpg': 'image/jpeg',
  34. '.jpeg': 'image/jpeg',
  35. '.png': 'image/png',
  36. '.gif': 'image/gif',
  37. '.wav': 'audio/wav',
  38. '.mp3': 'audio/mpeg',
  39. '.mp4': 'video/mp4',
  40. '.avi': 'video/x-msvideo',
  41. '.mov': 'video/quicktime'
  42. }
  43. return ext_to_mime.get(ext, 'application/octet-stream')
  44. except Exception as e:
  45. raise Exception(f"文件类型检测失败: {str(e)}")