使用前先安装oss2模块pip install oss2
两个参数第一个本地绝对路径,第二个远程路径,注意第一个字符不要使用 /import os
import oss2
import sys
"""进度条回调函数,计算当前完成的百分比
:param consumed_bytes: 已经上传/下载的数据量
:param total_bytes: 总数据量
"""
def percentage(consumed_bytes, total_bytes):
if total_bytes:
sys.stdout.write('{0:.2f}% {1:.2f}/{2:.2f}M\r'.format(100 * (consumed_bytes / total_bytes),
consumed_bytes / 1000000, total_bytes / 1000000))
sys.stdout.flush()
# 本地路径 D:/a/a.zip
# 远程路径 bak/a/
# 文件名自动取本地路径文件名
def uploadoss(localfile, remotePath):
if not os.path.exists(localfile):
print('localfile is not exists!')
return
AccessKeyID = 'LTA******MeT'
AccessKeySecret = 'aOLFL***********VAuXA1sKGKB'
endpoint = 'oss-cn********.com'
bucketName = 'xi********ve'
print("start uploadoss...")
auth = oss2.Auth(AccessKeyID, AccessKeySecret)
bucket = oss2.Bucket(auth, endpoint, bucketName, enable_crc=False)
osspath = remotePath + os.path.basename(localfile)
print("uploading to %s" % (osspath))
with open(localfile, 'rb') as fileobj:
bucket.put_object(osspath, fileobj, progress_callback=percentage)
print('\nuploadoss success!')
if __name__ == '__main__':
uploadoss('E:/wok.zip', 'bak/a/')
input('...')