s3_3_4.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. def upload_files_to_s3_with_key(
  2. self, file_path, file_name, is_private, parent_doctype, parent_name
  3. ):
  4. """
  5. Uploads a new file to S3.
  6. Strips the file extension to set the content_type in metadata.
  7. """
  8. mime_type = magic.from_file(file_path, mime=True)
  9. key = self.key_generator(file_name, parent_doctype, parent_name)
  10. content_type = mime_type
  11. try:
  12. if is_private:
  13. self.S3_CLIENT.upload_file(
  14. file_path, self.BUCKET, key,
  15. ExtraArgs={
  16. "ContentType": content_type,
  17. "Metadata": {
  18. "ContentType": content_type,
  19. "file_name": file_name
  20. }
  21. }
  22. )
  23. else:
  24. self.S3_CLIENT.upload_file(
  25. file_path, self.BUCKET, key,
  26. ExtraArgs={
  27. "ContentType": content_type,
  28. "ACL": 'public-read',
  29. "Metadata": {
  30. "ContentType": content_type,
  31. }
  32. }
  33. )
  34. except boto3.exceptions.S3UploadFailedError:
  35. frappe.throw(frappe._("File Upload Failed. Please try again."))
  36. return key