fileuploader.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # -*- coding: utf-8 -*-
  2. import os
  3. from typing import Union, Dict, Any
  4. import oss2
  5. import requests
  6. from core.config import settings
  7. class OSSFileUploader(object):
  8. def __init__(self, access_key_id: str, access_key_secret: str, bucket_name: str, root_name: str,
  9. endpoint: str, domain: str):
  10. self.AccessKeyID = access_key_id
  11. self.AccessKeySecret = access_key_secret
  12. self.bucket_name = bucket_name
  13. self.root_name = root_name
  14. self.auth = oss2.Auth(self.AccessKeyID, self.AccessKeySecret)
  15. self.endpoint = endpoint
  16. self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name)
  17. self.domain = domain
  18. def get_url(self, status_code: int, filename: str) -> str:
  19. return os.path.join(self.domain, filename) if status_code == 200 else ""
  20. def upload_from_str(self, filename: str, content: Union[bytes, str], content_type: Dict[str,
  21. Any]):
  22. """
  23. 通过字符串上传, byte, str
  24. """
  25. filename = os.path.join(self.root_name, filename)
  26. resp = self.bucket.put_object(filename, content, headers=content_type)
  27. return self.get_url(resp.status, filename)
  28. def upload_from_file(self, localfile: str, ossfile: str, content_type: Dict[str, Any]):
  29. """
  30. 上传本地文件到oss
  31. """
  32. ossfile = os.path.join(self.root_name, ossfile)
  33. with open(localfile, "rb") as f:
  34. resp = self.bucket.put_object(ossfile, f, headers=content_type)
  35. return self.get_url(resp.status, ossfile)
  36. def resumable_upload_from_local(self, localfile: str, ossfile: str, content_type: Dict[str,
  37. Any]):
  38. ossfile = os.path.join(self.root_name, ossfile)
  39. resp = oss2.resumable_upload(self.bucket,
  40. ossfile,
  41. localfile,
  42. headers=content_type,
  43. store=oss2.ResumableStore(root='/tmp'),
  44. multipart_threshold=100 * 1024,
  45. part_size=100 * 1024,
  46. num_threads=4)
  47. return self.get_url(resp.status, ossfile)
  48. def upload_from_url(self, fileurl: str, ossfile: str, content_type: Dict[str, Any]):
  49. """
  50. 通过URL上传
  51. """
  52. ossfile = os.path.join(self.root_name, ossfile)
  53. resp = self.bucket.put_object(ossfile, requests.get(fileurl), headers=content_type)
  54. return self.get_url(resp.status, ossfile)
  55. def delete_file(self, filename: str):
  56. resp = self.bucket.delete_object(filename)
  57. return True if resp.status == 200 else False
  58. def get_preview_url(self, fileurl: str) -> str:
  59. filename = fileurl.replace(f"{self.domain}/", "")
  60. style_str = "imm/previewdoc,copy_0"
  61. expire = 60 * 10
  62. url = self.bucket.sign_url("GET", filename, expire, params={"x-oss-process": style_str})
  63. return url
  64. ossfile_uploader = OSSFileUploader(
  65. settings.OSSINFO["AccessKeyID"],
  66. settings.OSSINFO["AccessKeySecret"],
  67. settings.OSSINFO["BucketName"],
  68. settings.OSSINFO["RootName"],
  69. settings.OSSINFO["Endpoint"],
  70. settings.OSSINFO["Domain"],
  71. )
  72. __all__ = ["ossfile_uploader"]
  73. if __name__ == '__main__':
  74. myoss = OSSFileUploader(
  75. "LTAIbkpKrzQViemJ",
  76. "9y9mqNFMMDfUEBGvWqHt3wGas2W5ML",
  77. "scxjcclub",
  78. "say365",
  79. "http://oss-cn-beijing.aliyuncs.com",
  80. 'http://scxjcclub.oss-cn-beijing.aliyuncs.com',
  81. )
  82. # with open("../ttt.txt", "rb") as f:
  83. # url = myoss.upload_from_str("oohtest.png",
  84. # base64.b64decode(f.read()),
  85. # content_type={"Content-Type": "image/png"})
  86. # localfile = '/tmp/test.txt'
  87. # ossfile = 'test/test.txt'
  88. # url = myoss.resumable_upload_from_local(localfile, ossfile)
  89. # 获取预览URL
  90. preview_url = myoss.get_preview_url("say365/高中数学人教A版必修5导学案-1.1正弦定理.doc")
  91. print(preview_url)