upload_to_oss.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import oss2
  4. import requests
  5. import uuid
  6. # from common import convert_to_pdf
  7. class MyOSS:
  8. def __init__(self):
  9. self.AccessKeyID = 'LTAIPp6YI1JUzpz2'
  10. self.AccessKeySecret = 'UWc04c4TpUeVot9cYqbkRpU4YhE25S'
  11. self.bucket_name = 'tederen'
  12. self.root_name = 'xdcjing'
  13. self.auth = oss2.Auth(self.AccessKeyID, self.AccessKeySecret)
  14. self.endpoint = 'http://oss-cn-shanghai.aliyuncs.com'
  15. self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name)
  16. self.domain = 'http://tederen.oss-cn-shanghai.aliyuncs.com'
  17. def upload_from_str(self,content_str=None,filename=None):
  18. '''
  19. 通过字符串上传
  20. byte,unicode,str
  21. '''
  22. filename = os.path.join(self.root_name,filename)
  23. result = self.bucket.put_object(filename,content_str)
  24. if result.status == 200:
  25. url = os.path.join(self.domain,filename)
  26. else:
  27. url = ''
  28. return url
  29. def upload_from_local(self, localfile=None, ossfile=None):
  30. '''
  31. 上传本地文件到oss
  32. '''
  33. ossfile = os.path.join(self.root_name, ossfile)
  34. with open(localfile, 'rb') as fileobj:
  35. result = self.bucket.put_object(ossfile, fileobj)
  36. if result.status == 200:
  37. url = os.path.join(self.domain, ossfile)
  38. else:
  39. url = ''
  40. return url
  41. def resumable_upload_from_local(self, localfile=None, ossfile=None):
  42. ossfile = os.path.join(self.root_name, ossfile)
  43. result = oss2.resumable_upload(self.bucket,ossfile,localfile,
  44. store=oss2.ResumableStore(root='/tmp'),
  45. multipart_threshold=100*1024,
  46. part_size=100*1024,
  47. num_threads=4,
  48. progress_callback=self.progress_callback
  49. )
  50. if result.status == 200:
  51. url = os.path.join(self.domain,ossfile)
  52. else:
  53. url = ''
  54. return url
  55. def upload_from_url(self, url=None, ossfile=None):
  56. '''
  57. '''
  58. ossfile = os.path.join(self.root_name,ossfile)
  59. resp = requests.get(url)
  60. result = self.bucket.put_object(ossfile,resp)
  61. if result.status == 200:
  62. url = os.path.join(self.domain,ossfile)
  63. else:
  64. url = ''
  65. return url
  66. def upload_from_ajax(self, request, path_name, key):
  67. """
  68. 上传文件
  69. :param request: 请求
  70. :param path_name: 要存放到服务器上的路径
  71. :param key: 从request取文件的form的name
  72. :return: dict
  73. """
  74. file_obj = request.FILES.get(key, None)
  75. if file_obj:
  76. file_name = file_obj.name.split(".")[0]
  77. file_type = file_obj.name.split(".")[-1]
  78. file_size = file_obj.size
  79. origin_file_name = path_name + str(uuid.uuid1()) + '.' + file_type
  80. pdf_file_name = path_name + str(uuid.uuid1()) + '.pdf'
  81. # 把文件写入tmp,上传到server后,删除本地
  82. tmp_file_name = os.path.join("/tmp", file_obj.name)
  83. print "tmp_file_name --> ", tmp_file_name
  84. with open(tmp_file_name, "wb+") as fobj:
  85. for chunk in file_obj.chunks():
  86. fobj.write(chunk)
  87. file_url = MyOSS().resumable_upload_from_local(tmp_file_name,
  88. origin_file_name)
  89. result = {"name": file_name, "type": file_type,
  90. "size": file_size, "url": file_url}
  91. # 只有资源、任务才进行转换
  92. if key in ["resource", "task", "url"]:
  93. res = convert_to_pdf(tmp_file_name)
  94. print "convert result: -->", res
  95. # 转换为pdf,再次上传到server
  96. tmp_pdf_name = os.path.join("/tmp", file_name + ".pdf")
  97. print "tmp_pdf_name --> ", tmp_pdf_name
  98. if res:
  99. pdf_file_url = MyOSS().resumable_upload_from_local(tmp_pdf_name,
  100. pdf_file_name)
  101. if pdf_file_url:
  102. result["pdf_url"] = pdf_file_url
  103. os.remove(tmp_pdf_name)
  104. # 删除源文件
  105. if file_url:
  106. os.remove(tmp_file_name)
  107. print "upload_file_info: --> ", result
  108. else:
  109. result = {}
  110. return result
  111. def progress_callback(self, consumed_bytes, total_bytes):
  112. if total_bytes:
  113. rate = int(100*float(consumed_bytes)/float(total_bytes))
  114. if rate % 50 == 0:
  115. print '\r{0}%'.format(rate)
  116. if __name__ == '__main__':
  117. myoss = MyOSS()
  118. #url = myoss.upload_from_str('test','test/test.txt')
  119. #print url
  120. #localfile = 'localtest.txt'
  121. #ossfile = 'localtooss/text.txt'
  122. #url = myoss.upload_from_local(localfile,ossfile)
  123. #print url
  124. #ossfile = 'test/test.jpg'
  125. #url = myoss.upload_from_url('http://img.ph.126.net/ocT0cPlMSiTs2BgbZ8bHFw==/631348372762626203.jpg',ossfile)
  126. #print url
  127. localfile = 'test.mp4'
  128. ossfile = 'localtooss/test.mp4'
  129. url = myoss.resumable_upload_from_local(localfile,ossfile)
  130. print url