import oss2 auth = oss2.Auth('xxx', 'xxx') #详见文档 endpoint = 'http://oss-cn-beijing.aliyuncs.com' # 地址 bucket = oss2.Bucket(auth, endpoint, 'xxxxFDnjet') # 项目名称 def uplaod(): result = bucket.put_object_from_file('xxx.jpg','/xx/xxxx.jpg')# 括号内 左边是上传到服务器的文件名,右边是当前系统的文件路径 print(result.status) # 如果状态码是200表示上传成功 # 这个就是返回url的方法,它需要携带着你的 ACCESS_KEY_ID, ACCESS_KEY_SECRET去获取临时的权限, jpg_url = bucket.sign_url('GET','Zabbix_Graph.jpg',60) #阿里返回一个关于Zabbix_Graph.jpg的url地址 60是链接60秒有效 print(jpg_url)
import oss2, uuid from config.config import ALIYUN_OSS_SETTING class AliyunOss(object): def __init__(self): self.access_key_id = "你的ACCESS_KEY_ID" self.access_key_secret = "你的ACCESS_KEY_SECRET" self.auth = oss2.Auth(self.access_key_id, self.access_key_secret) self.bucket_name = "你的BUCKET_NAME" self.endpoint = "你的ENDPOINT" self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name) def put_file(self, name, file): """ :param name: 文件名 :param file: 文件 :return: """ # Endpoint以杭州为例,其它Region请按实际情况填写。 result = self.bucket.put_object(name, file) # HTTP返回码。 print('http status: {0}'.format(result.status)) # 请求ID。请求ID是请求的唯一标识,强烈建议在程序日志中添加此参数。 print('request_id: {0}'.format(result.request_id)) # ETag是put_object方法返回值特有的属性。 print('ETag: {0}'.format(result.etag)) # HTTP响应头部。 print('date: {0}'.format(result.headers['date'])) def put_object_from_file(self, name, file): """ 上传本地文件 :param name: 需要上传的文件名 :param file: 本地文件名 :return: 阿里云文件地址 """ self.bucket.put_object_from_file(name, file) return "https://{}.{}/{}".format(self.bucket_name, self.endpoint, name) def put_object(self, name, file): # 上传二进制文件 self.bucket.put_object(name, file) return "https://{}.{}/{}".format(self.bucket_name, self.endpoint, name) aliyunoss = AliyunOss() # img = aliyunoss.put_object("传到阿里云上的图片名", "二进制图片") img = aliyunoss.put_object_from_file("传到阿里云上的图片名", "本地图片路径")
至于上传PIL对象图片上传,我是直接把图片转成二进制再上传的,代码如下:
img = "你的img" imgByteArr = io.BytesIO() img.save(imgByteArr, format='PNG') imgByte = imgByteArr.getvalue()