对象大于 5GiB 时,您可以使用分片拷贝。
对象大于 5GiB 时,需要使用 upload_part_copy 来进行分片拷贝,包括三个步骤:
以下代码用于拷贝 src_bucket_name
桶中 src_object_key
对象到 bucket_name
桶中,并设置对象名为 object_key
。
import os import tos from tos.models2 import UploadedPart # 从环境变量获取 AK 和 SK 信息。 ak = os.getenv('TOS_ACCESS_KEY') sk = os.getenv('TOS_SECRET_KEY') # your endpoint 和 your region 填写Bucket 所在区域对应的Endpoint。# 以华北2(北京)为例,your endpoint 填写 tos-cn-beijing.volces.com,your region 填写 cn-beijing。 endpoint = "your endpoint" region = "your region" # 目标桶的名称 bucket_name = "bucket-test" # 拷贝到目标桶后的对象名称 object_key = "object-test" # 源桶的名称 src_bucket_name = "your src bucket name" # 源对象的名称 src_object_key = "your src object key" try: # 创建 TosClientV2 对象,对桶和对象的操作都通过 TosClientV2 实现 client = tos.TosClientV2(ak, sk, endpoint, region) # 获取 桶 src_bucket 中已存在对象 src_object 的大小 head_info = client.head_object(src_bucket_name, src_object_key) total_size = head_info.content_length part_size = 1024 * 1024 * 5 # 初始化一个 Multipart 任务 resp = client.create_multipart_upload(bucket_name, object_key) upload_id = resp.upload_id # 拷贝分片 parts = [] part_number = 1 offset = 0 while offset < total_size: num_to_upload = min(part_size, total_size - offset) end = offset + num_to_upload - 1 result = client.upload_part_copy(bucket_name, object_key, upload_id, part_number, src_bucket_name, src_object_key, copy_source_range_start=offset, copy_source_range_end=end) parts.append(UploadedPart(part_number, result.etag)) offset += num_to_upload part_number += 1 # 完成分片拷贝。 resp = client.complete_multipart_upload(bucket_name, object_key, upload_id, parts=parts) except tos.exceptions.TosClientError as e: # 操作失败,捕获客户端异常,一般情况为非法请求参数或网络异常 print('fail with client error, message:{}, cause: {}'.format(e.message, e.cause)) except tos.exceptions.TosServerError as e: # 操作失败,捕获服务端异常,可从返回信息中获取详细错误信息 print('fail with server error, code: {}'.format(e.code)) # request id 可定位具体问题,强烈建议日志中保存 print('error with request id: {}'.format(e.request_id)) print('error with message: {}'.format(e.message)) print('error with http code: {}'.format(e.status_code)) print('error with ec: {}'.format(e.ec)) print('error with request url: {}'.format(e.request_url)) except Exception as e: print('fail with unknown error: {}'.format(e))