oss_utils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import os
  2. import requests
  3. import mimetypes
  4. def upload_to_oss(file_path, custom_filename=None):
  5. """
  6. Uploads a file to OSS using the provided API endpoint.
  7. URL: https://crmapi.dcjxb.yunzhixue.cn/file/upload
  8. Method: POST
  9. Form-data: parameter 'file'
  10. """
  11. url = "https://crmapi.dcjxb.yunzhixue.cn/file/upload"
  12. try:
  13. filename = custom_filename if custom_filename else os.path.basename(file_path)
  14. mime_type, _ = mimetypes.guess_type(file_path)
  15. if not mime_type:
  16. mime_type = 'application/octet-stream'
  17. with open(file_path, 'rb') as f:
  18. files = {'file': (filename, f, mime_type)}
  19. response = requests.post(url, files=files)
  20. response.raise_for_status()
  21. result = response.json()
  22. # Assuming the response contains the URL in a specific field
  23. if result.get('code') == 200 or result.get('success'):
  24. # Extract URL - adjusting based on common API patterns
  25. data = result.get('data', {})
  26. if isinstance(data, str):
  27. return data
  28. return data.get('url') or data.get('fileUrl') or result.get('url')
  29. else:
  30. print(f"Upload failed: {result}")
  31. return None
  32. except Exception as e:
  33. print(f"Error uploading to OSS: {e}")
  34. return None