Help Center/ Object Storage Service/ SDK Reference/ iOS/ Object Upload/ Pausing and Resuming/Aborting a Resumable Upload
Updated on 2024-12-09 GMT+08:00

Pausing and Resuming/Aborting a Resumable Upload

Uploading a large file often fail due to an unstable network or program breakdown. Uploading the file again wastes lots of resources. Moreover, the repeated uploads may still fail due to an unstable network. The resumable upload interface is designed to address this problem. This interface splits a file into multiple parts and uploads them separately. The upload result of each part is recorded in a checkpoint file in real time. Only when all parts are successfully uploaded will a success response be returned. Otherwise, an exception is thrown reminding you to call the interface again. When the upload is resumed, you only need to upload the failed parts based on the checkpoint file, which helps save resources and improve efficiency.

You can call the uploadFile interface to perform a resumable upload. The configurable parameters of this interface are as follows:

Parameter

Description

Method in OBS iOS SDK

bucketName

(Mandatory) Bucket name

request.bucketName

objectKey

(Mandatory) Object name

request.objectKey

objectACLPolicy

Object access control policy

request.objectACLPolicy

storageClass

Object storage class

request.storageClass

metaDataDict

Object metadata

request.metaDataDict

websiteRedirectLocation

Redirection location of a website

request.websiteRedirectLocation

encryption

Encryption mode

request.encryption

enableCheckpoint

Whether to enable the resumable mode. The default value is NO.

request.enableCheckpoint

enableMD5Check

Whether to enable MD5 verification. The default value is NO.

request.enableMD5Check

checkpointFilePath

Path of the file that records the upload progress. This parameter is effective only in the resumable mode. If the value is null, the file is in the same directory as the local file to be uploaded. The file name extension can be set to obsuploadcheckpoint.

request.checkpointFilePath

partSize

Part size, in bytes. The value ranges from 100KB to 5GB and defaults to 5MB.

request.partSize

needAbortUploadFileAfterCancel

Whether to cancel the entire upload when a resumable upload is paused

request.needAbortUploadFileAfterCancel

The following code shows how to call the interface to pause and resume a resumable upload:

#import <OBS/OBS.h>
void testPauseAndResumeUploadFile(){
    static OBSClient *client;
    NSString *endPoint = @"your-endpoint";
    // Hard-coded or plaintext AK/SK are risky. For security purposes, encrypt your AK/SK and store them in the configuration file or environment variables. In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, configure environment variables AccessKeyID and SecretAccessKey in your local environment.
    // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
    char* ak_env = getenv("AccessKeyID");
    char* sk_env = getenv("SecretAccessKey");
    NSString *AK = [NSString stringWithUTF8String:ak_env];
    NSString *SK = [NSString stringWithUTF8String:sk_env];
        
    // Initialize identity authentication.
    OBSStaticCredentialProvider *credentialProvider = [[OBSStaticCredentialProvider alloc] initWithAccessKey:AK secretKey:SK];
        
    // Initialize service configuration.
    OBSServiceConfiguration *conf = [[OBSServiceConfiguration alloc] initWithURLString:endPoint credentialProvider:credentialProvider];
        
    // Initialize the client.
    client = [[OBSClient alloc] initWithConfiguration:conf];
        
    // Set the maximum number of concurrent requests.
    client.configuration.maxConcurrentUploadRequestCount = 5;
    // Set the maximum number of concurrent connections.
    client.configuration.uploadSessionConfiguration.HTTPMaximumConnectionsPerHost = 10;
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"localFile" ofType:@"fileType"];
    OBSUploadFileRequest *request = [[OBSUploadFileRequest alloc]initWithBucketName:@"your-bucket-name" objectKey:@"objectname" uploadFilePath:filePath];
    // Set the part size to 5MB.
    request.partSize = [NSNumber numberWithInteger: 5 * 1024*1024];
    // Enable the resumable mode.
    request.enableCheckpoint = YES;
    // Specify the checkpoint file path. This parameter is optional.
//    request.checkpointFilePath = @"Your CheckPoint File";
        
    // Upload a file.
    request.uploadProgressBlock =  ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%0.1f%%",(float)floor(totalBytesSent*10000/totalBytesExpectedToSend)/100);
    };
        
    OBSBFTask  *task = [client uploadFile:request completionHandler:^(OBSUploadFileResponse *response, NSError *error) {
        if(error){
            // Print the error information when the upload is paused.
            NSLog(@"upload file failed:%@", error);
        }
        if(response){
            NSLog(@"upload file response:%@", response);
        }
    }];
    // Pause the upload one second after it starts.
    sleep(1);
    [request cancel];
    // Allow the upload to resume from the breakpoint.
    [task waitUntilFinished];
    task = [client uploadFile:request completionHandler:^(OBSUploadFileResponse *response, NSError *error) {
        if(error){
            NSLog(@"upload file failed:%@", error);
            // Resume the upload.
        }
        if(response){
            NSLog(@"upload file response:%@", response);
        }
    }];
    [task waitUntilFinished];
}

The following code shows how to call the interface to pause and abort a resumable upload:

#import <OBS/OBS.h>
void testPauseAndAbortUploadFile() {
    static OBSClient *client;
    NSString *endPoint = @"your-endpoint";
    // Hard-coded or plaintext AK/SK are risky. For security purposes, encrypt your AK/SK and store them in the configuration file or environment variables. In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, configure environment variables AccessKeyID and SecretAccessKey in your local environment.
    // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
    char* ak_env = getenv("AccessKeyID");
    char* sk_env = getenv("SecretAccessKey");
    NSString *AK = [NSString stringWithUTF8String:ak_env];
    NSString *SK = [NSString stringWithUTF8String:sk_env];
        
    // Initialize identity authentication.
    OBSStaticCredentialProvider *credentialProvider = [[OBSStaticCredentialProvider alloc] initWithAccessKey:AK secretKey:SK];
        
    // Initialize service configuration.
    OBSServiceConfiguration *conf = [[OBSServiceConfiguration alloc] initWithURLString:endPoint credentialProvider:credentialProvider];
        
    // Initialize the client.
    client = [[OBSClient alloc] initWithConfiguration:conf];
        
    // Set the maximum number of concurrent requests.
    client.configuration.maxConcurrentUploadRequestCount = 5;
    // Set the maximum number of concurrent connections.
    client.configuration.uploadSessionConfiguration.HTTPMaximumConnectionsPerHost = 10;
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"localFile" ofType:@"fileType"];
    OBSUploadFileRequest *request = [[OBSUploadFileRequest alloc]initWithBucketName:@"your-bucket-name" objectKey:@"objectname" uploadFilePath:filePath];
    // Set the part size to 5MB.
    request.partSize = [NSNumber numberWithInteger: 5 * 1024*1024];
    // Enable the resumable mode.
    request.enableCheckpoint = YES;
    // Specify the checkpoint file path. This parameter is optional.
//    request.checkpointFilePath = @"Your CheckPoint File";
        
    // Upload a file.
    request.uploadProgressBlock =  ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%0.1f%%",(float)floor(totalBytesSent*10000/totalBytesExpectedToSend)/100);
    };
    // Abort the upload after it is paused.
    request.needAbortUploadFileAfterCancel = YES;
        
    OBSBFTask  *task = [client uploadFile:request completionHandler:^(OBSUploadFileResponse *response, NSError *error) {
        if(error){
            // Print the error information when the upload is paused.
            NSLog(@"upload file failed:%@", error);
        }
        if(response){
            NSLog(@"upload file response:%@", response);
        }
    }];
    // Pause and abort the upload one second after it starts.
    sleep(1);
    [request cancel];
    // Start the upload from scratch.
    [task waitUntilFinished];
    task = [client uploadFile:request completionHandler:^(OBSUploadFileResponse *response, NSError *error) {
        if(error){
            NSLog(@"upload file failed:%@", error);
            // Upload the file again.
        }
        if(response){
            NSLog(@"upload file response:%@", response);
        }
    }];
    [task waitUntilFinished];
}
  • The resumable upload interface is based on the multipart upload interface.
  • The resumable upload interface helps save resources and improve efficiency by restarting an upload from the point of failure and concurrently uploading parts. You do not need to worry about internal service details, such as the creation and deletion of checkpoint files, division of objects, or concurrent uploads of parts.
  • The default value of the enableCheckpoint parameter is NO, which indicates that the resumable upload mode is disabled. In this case, a resumable upload is a multipart upload, with no checkpoint files generated.
  • checkpointFile is effective only when enableCheckpoint is YES.
  • If you need to perform multiple resumable uploads at the same time, you need to initialize an instance of OBSClient and a request for each upload.
  • The default value of needAbortUploadFileAfterCancel is NO. If you retain that default value and also set enableCheckpoint to YES, when a resumable upload is paused, it will not be aborted, and the uploaded parts will not be discarded. In any other cases, the multipart upload will be aborted.