Python 实现 OSS 文件上传追加断点续传的示例代码,带有进度条

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!')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少陽君

谢谢老板的拿铁

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值