CommonUtils.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Created on 2017-12-20
  4. @author: liuqun
  5. '''
  6. from alipay.aop.api.constant.CommonConstants import PYTHON_VERSION_3
  7. def has_value(m, key):
  8. if not m:
  9. return False
  10. if not (key in m):
  11. return False
  12. if not m[key]:
  13. return False
  14. return True
  15. def get_file_suffix(bs):
  16. if not bs or len(bs) < 10:
  17. return None
  18. if PYTHON_VERSION_3:
  19. if bs[0] == 71 and bs[1] == 73 and bs[2] == 70:
  20. return "GIF"
  21. if bs[1] == 80 and bs[2] == 78 and bs[3] == 71:
  22. return "PNG"
  23. if bs[6] == 74 and bs[7] == 70 and bs[8] == 73 and bs[9] == 70:
  24. return "JPG"
  25. if bs[0] == 66 and bs[1] == 77:
  26. return "BMP"
  27. else:
  28. if ord(bs[0]) == 71 and ord(bs[1]) == 73 and ord(bs[2]) == 70:
  29. return "GIF"
  30. if ord(bs[1]) == 80 and ord(bs[2]) == 78 and ord(bs[3]) == 71:
  31. return "PNG"
  32. if ord(bs[6]) == 74 and ord(bs[7]) == 70 and ord(bs[8]) == 73 and ord(bs[9]) == 70:
  33. return "JPG"
  34. if ord(bs[0]) == 66 and ord(bs[1]) == 77:
  35. return "BMP"
  36. return None
  37. def get_mime_type(bs):
  38. suffix = get_file_suffix(bs)
  39. mime_type = "application/octet-stream"
  40. if suffix == "JPG":
  41. mime_type = "image/jpeg"
  42. elif suffix == "GIF":
  43. mime_type = "image/gif"
  44. elif suffix == "PNG":
  45. mime_type = "image/png"
  46. elif suffix == "BMP":
  47. mime_type = "image/bmp"
  48. return mime_type