You need to enable JavaScript to run this app.
导航
分片上传(iOS SDK)
最近更新时间:2024.02.04 18:30:59首次发布时间:2022.11.21 19:11:16

对于较大的对象,可以分成多个数据块(part)来分别上传,最后调用CompleteMultipartUpload来把上传的数据块合并为一个对象。

分片上传步骤

您可以通过以下步骤分片上传对象:

  1. 通CreateMultipartUpload 初始化分片上传任务。
  2. 通过 UploadPart 进行分片上传。
  3. 通过 CompleteMultipartUpload 将所有分片合并为一个对象。

示例代码

如下代码展示如何通过分片接口分片上传一个对象。

// 从STS服务获取的临时访问密钥和安全令牌(AccessKey、SecretKey、SecurityToken)
TOSCredential *credential = [[TOSCredential alloc] initWithAccessKey:@"accesskey" secretKey:@"secretkey" securityToken:@"securityToken"];
TOSEndpoint *tosEndpoint = [[TOSEndpoint alloc] initWithURLString:@"endpoint" withRegion:@"region"];
TOSClientConfiguration *config = [[TOSClientConfiguration alloc] initWithEndpoint:tosEndpoint credential:credential];
TOSClient *client = [[TOSClient alloc] initWithConfiguration:config];

// 1. CreateMultipartUpload
TOSCreateMultipartUploadInput *create = [TOSCreateMultipartUploadInput new];
create.tosBucket = @"bucket-name";
create.tosKey = @"object-name";

TOSTask *task = [client createMultipartUpload:create];
[task waitUntilFinished];
TOSCreateMultipartUploadOutput *createOutput = task.result;

// 2. UploadPart
NSMutableArray *uploadedParts = [NSMutableArray array];
for (int i = 1; i <= your_chunck_count; i++) {
    TOSUploadPartInput *upload = [TOSUploadPartInput new];
    upload.tosKey = createOutput.key;
    upload.tosBucket = createOutput.bucket;
    upload.tosUploadId = createOutput.uploadId;
    upload.tosPartNumber = i;
    upload.tosContent = your_chunck_data;
    task = [client uploadPart:upload];
    [task waitUntilFinished];
    TOSUploadPartOutput *uploadOutput = task.result;
    // 保存ETag和PartNumber
    TOSUploadedPart *uploadedPart = [TOSUploadedPart new];
    uploadedPart.tosETag = uploadOutput.tosETag; // 注意处理首尾\"
    uploadedPart.tosPartNumber = uploadOutput.tosPartNumber;
    
    [uploadedParts addObject:uploadedPart];
}

// 3. CompleteMultipartUpload
TOSCompleteMultipartUploadInput *complete = [TOSCompleteMultipartUploadInput new];
complete.tosBucket = createOutput.bucket;
complete.toKey = createOutput.key;
complete.tosUploadId = createOutput.uploadId;
complete.tosParts = uploadedParts; // 根据保存的ETag和PartNumber构建
task = [client completeMultipartUpload:complete];
[task continueWithBlock:^id(TOSTask *task) {
    if (!task.error) {
        TOSCompleteMultipartUploadOutput *completeOutput = task.result;
    } else {
    }
    return nil;
}];