最近正好写了一个 你可以参考一下。第一个文件:专门用于阿里云oss的代码:
import os
import json
from PIL import Image
import oss2
import hashlib
access_key_id = "xxx"
access_key_secret = "xxx"
bucket_name = "gmooc-videos"
endpoint = "http://oss-cn-beijing.aliyuncs.com"
domain = "https://gmooc-videos.oss-accelerate.aliyuncs.com/"
bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)
def get_md5(data):
m2 = hashlib.md5()
m2.update(data.encode('utf-8'))
return m2.hexdigest()
# 确认上面的参数都填写正确了
for param in (access_key_id, access_key_secret, bucket_name, endpoint):
assert '<' not in param, '请设置参数:' + param
def get_image_info(image_file):
"""获取本地图片信息
:param str image_file: 本地图片
:return tuple: a 3-tuple(height, width, format).
"""
im = Image.open(image_file)
return im.height, im.width, im.format
def upload_single_image(file_path, file_name):
# 创建Bucket对象,所有Object相关的接口都可以通过Bucket对象来进行
md5_str = get_md5(file_name)
key = "{}/{}".format(md5_str, file_name)
# 上传示例图片
# bucket.put_object_from_file(key, file_name)
bucket.put_object_from_file(key, file_path, headers={
"Content-Type": "image/jpg"
})
bucket.put_object_acl(key, oss2.BUCKET_ACL_PUBLIC_READ)
# 分类-多维度分类,文件名,id对应
"""
单文件
1. 文本内容
2. 附件
3. 图片管理
4. 封面管理
5. 分类管理
"""
return domain + key
def upload_single_file(file_path, file_name):
# 创建Bucket对象,所有Object相关的接口都可以通过Bucket对象来进行
md5_str = get_md5(file_name)
key = "{}/ppt/{}".format(md5_str, file_name)
# 上传示例图片
# bucket.put_object_from_file(key, file_name)
bucket.put_object_from_file(key, file_path, headers={
"Content-Type": "application/x.scratch.sb3"
})
bucket.put_object_acl(key, oss2.BUCKET_ACL_PUBLIC_READ)
# 分类-多维度分类,文件名,id对应
"""
单文件
1. 文本内容
2. 附件
3. 图片管理
4. 封面管理
5. 分类管理
"""
return domain + key
def upload_image(image_file_path, file_name):
image_urls = []
# 创建Bucket对象,所有Object相关的接口都可以通过Bucket对象来进行
i = 0
domain = "https://51ppt.oss-cn-hangzhou.aliyuncs.com/"
md5_str = get_md5(file_name)
key = "{}/{}".format(md5_str, file_name)
# 上传示例图片
# bucket.put_object_from_file(key, file_name)
bucket.put_object_from_file(key, image_file_path, headers={
"Content-Type":"image/jpg"
})
bucket.put_object_acl(key, oss2.BUCKET_ACL_PUBLIC_READ)
#分类-多维度分类,文件名,id对应
return domain+key
# 获取图片信息
# result = bucket.get_object(key, process='image/info')
# a = 1
# break
if __name__ == "__main__":
# upload_image("test.pptx", "D:/ppt建站/ppt_presenter/ali_oss")
file_path = "D:/python微服务/projects/GeekMind/media/projects/2020/04/blob_0bUw5b3"
file_name = file_path.split('/')[-1]
url = upload_single_file(file_path,file_name)
print(url)
具体配置你需要配置自己的信息
然后xadmin中:
def save_models(self):
import os
obj = self.new_obj
obj.save()
file_path = obj.file.path #获取本地文件
file_name = file_path.split(os.path.sep)[-1]
url = upload_single_file(file_path, file_name)
obj.ali_url = url
obj.save()
上面的逻辑希望你能看懂