Python 上传文件到阿里云OSS云存储

python  

安装SDK

pip install oss2  

上传文件到OSS

# -*- coding: utf-8 -*-

import os  
from datetime import datetime

import oss2


# 以下代码展示了一些和文件相关的高级用法,如中文、设置用户自定义元数据、拷贝文件、追加上传等。


# 首先初始化AccessKeyId、AccessKeySecret、Endpoint等信息。
# 通过环境变量获取,或者把诸如“<你的AccessKeyId>”替换成真实的AccessKeyId等。
access_key_id = os.getenv('OSS_TEST_ACCESS_KEY_ID', 'xxxxxxxxxxxxx')  
access_key_secret = os.getenv('OSS_TEST_ACCESS_KEY_SECRET', 'xxxxxxxxxxxxxxx')  
bucket_name = os.getenv('OSS_TEST_BUCKET', 'xxxx-test')  
endpoint = os.getenv('OSS_TEST_ENDPOINT', 'oss-cn-shenzhen.aliyuncs.com')  
base_file_url = 'xxxxx-test.oss-cn-shenzhen.aliyuncs.com'  
bucket_folder = 'test/'     #bucket_folder = 'test/'

# 确认上面的参数都填写正确了
for param in (access_key_id, access_key_secret, bucket_name, endpoint):  
    assert '<' not in param, '请设置参数:' + param


# 创建Bucket对象,所有Object相关的接口都可以通过Bucket对象来进行
bucket = oss2.Bucket(  
    oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)

def upload_oss_getUrl(project,file,file_name, name=None):  
    bucket_folder = '{}/'.format(project)  # bucket_folder = 'test/'
    #file_path = path

    oss_file_path = bucket_folder + file_name
    # 文件上传至oss
    res = bucket.put_object(oss_file_path, file)
    print(res)
    #bucket.put_object_from_file(oss_file_path, file_path)
    file_url = base_file_url+'/'+bucket_folder+file_name
    # 获取oss上的url
    #file_url = bucket.sign_url('GET', oss_file_path, 360)  # 360是链接360秒有效
    #print(file_url)
    return file_url


if __name__ == '__main__':  
    #upload_oss_getUrl = upload_oss_getUrl("./fldxc_zandou.txt")
    project="mytest"
    file="aaaaaaaaaa"
    file_name="a.txt"
    upload_oss_getUrl(project,file,file_name)