背景
登录账号上传较麻烦,使用脚本上传
实现代码
以下是使用 Python 3 写的上传文件到阿里云 OSS 上的代码,其中需要填写自己的 Access Key、Secret Key、Bucket 名称和上传地址
填写自己的 Access Key 和 Secret Key
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)
这段代码定义了一个 oss_upload_file 函数,将文件上传到指定的 OSS Bucket,并返回上传后的地址。可以通过调用这个函数来完成文件上传和返回地址的操作。需要将其中的 access_key_id、access_key_secret、bucket_name 和 upload_path 分别替换为自己的 Access Key、Secret Key、Bucket 名称和上传路径,具体可参考阿里云 OSS 文档。