import os
import math
import oss2
from tqdm import tqdm
# 配置OSS Bucket信息
auth = oss2.Auth('<Your AccessKeyId>', '<Your AccessKeySecret>')
bucket_name = '<Your Bucket Name>'
object_name = '<Your Object Name>' # 上传后的对象名称
file_path = '<Your File Path>' # 本地待上传文件路径
# 初始化OSS客户端
bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com', bucket_name)
# 获取已上传的分片信息
upload_id = None
parts = []
if os.path.exists(object_name + '.part'):
with open(object_name + '.part', 'r') as f:
upload_id = f.readline().strip()
for line in f.readlines():
if line.strip() == '':
continue
part_number, part_etag = line.strip().split('\t')
parts.append(oss2.models.PartInfo(int(part_number), part_etag))
# 如果不存在上传记录,则创建新的分片上传任务
if upload_id is None:
upload_id = bucket.init_multipart_upload(object_name).upload_id
# 分片上传文件
part_size = 50 * 1024 * 1024 # 每个分片的大小,这里设置为50MB
with open(file_path, 'rb') as f:
index = len(parts) + 1
file_size = os.path.getsize(file_path)
part_count = int(math.ceil(file_size / part_size))
with tqdm(total=file_size, unit='B', unit_scale=True, unit_divisor=1024) as pbar:
while True:
data = f.read(part_size)
if not data:
break
part = bucket.upload_part(
object_name,
upload_id,
index,
data
)
parts.append(oss2.models.PartInfo(index, part.etag))
uploaded_size = index * part_size
if uploaded_size > file_size:
uploaded_size = file_size
pbar.update(uploaded_size - pbar.n)
index += 1
# 将已上传的分片信息保存到本地
with open(object_name + '.part', 'w') as f:
f.write(upload_id + '\n')
for part in parts:
f.write('{}\t{}\n'.format(part.part_number, part.etag))
# 完成分片上传
result = bucket.complete_multipart_upload(
object_name,
upload_id,
parts
)
print('Upload successfully!')
Python 实现 OSS 文件上传追加断点续传的示例代码,带有进度条
最新推荐文章于 2024-08-13 04:23:28 发布