Python 上传文件到阿里云 OSS

发布时间 2023-08-09 01:54:21作者: 郭小睿

以下是使用 Python 3 写的上传文件到阿里云 OSS 上的代码,其中需要填写自己的 Access Key、Secret Key、Bucket 名称和上传地址
填写自己的 Access Key 和 Secret Key

pip install oss2
import oss2
access_key_id = '<AccessKeyId>'
access_key_secret = '<AccessKeySecret>'
 
# 填写自己的 Bucket 名称和上传地址
bucket_name = '<BucketName>'
upload_path = 'uploads/'
 
# 创建 OSS 链接
auth = oss2.Auth(access_key_id, access_key_secret)
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', bucket_name)
 
# 上传文件到 OSS
def oss_upload_file(file_path):
    # 构造上传路径
    file_name = os.path.basename(file_path)
    oss_path = upload_path + file_name
    # 上传文件
    with open(file_path, 'rb') as file_obj:
        result = bucket.put_object(oss_path, file_obj)
    # 返回上传地址
    return result.url
 
# 测试
file_path = '/path/to/your/file'
oss_url = oss_upload_file(file_path)
print(oss_url)