Updated on 2026-11-17 GMT+08:00

Multipart Upload APIs (SDK for C)

If you have any questions during development, post them on the Issues page of GitHub.

You can upload a large file using multipart upload. Multipart upload is applicable to many scenarios. The following are some examples.

  • A file to be uploaded is larger than 100 MB.
  • The network connection to the OBS server breaks often.
  • The size of a file to be uploaded is unknown.

A multipart upload consists of the following steps:

  1. Initiating a Multipart Upload (SDK for C)
  2. Uploading a Part (SDK for C)
  3. Assembling Parts (SDK for C) or Aborting a Multipart Upload (SDK for C)

Multipart upload is mainly used for large file upload or when the network connection is poor. This example uploads a large file in parts concurrently:

#include "eSDKOBS.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
// The response callback function. In this callback, you can record the content of properties into callback_data (custom callback data).
obs_status response_properties_callback(const obs_response_properties *properties, void *callback_data);
// The dedicated response callback for uploading parts (callback_data is passed as UploadPartTask*). It is used to record the ETags of parts.
obs_status upload_part_properties_callback(const obs_response_properties *properties, void *callback_data);
// The completion callback function (general, callback_data is passed as obs_status*). It is used to record the result status.
void response_complete_callback(obs_status status, const obs_error_details *error, void *callback_data);
// The dedicated completion callback for uploading parts (callback_data is passed as UploadPartTask*). It is used to record the result status of the multipart upload.
void upload_part_complete_callback(obs_status status, const obs_error_details *error, void *callback_data);
// Callback function for completing a multipart upload. It is used to return the assembling result.
obs_status complete_multipart_upload_callback(const char *location, const char *bucket,
                                              const char *key, const char *etag,
                                              void *callback_data);
// Callback function for uploading parts. The SDK uses this callback function to read parts.
int upload_part_data_callback(int buffer_size, char *buffer, void *callback_data);
// Worker thread: Obtains multipart upload tasks from the queue and performs the upload.
void *upload_part_worker(void *arg);
#define PART_SIZE (5 * 1024 * 1024)   // Each part is 5 MB.
#define MAX_PARTS  10000              // Maximum number of parts
#define THREAD_NUM 5                 // Number of concurrent multipart upload tasks
// Data of a single multipart upload task
typedef struct UploadPartTask
{
    obs_options *options;            // options of the main thread is reused.
    char *key;                       // Object name
    char *upload_id;                 // Multipart upload task ID
    unsigned int part_number;        // Part number
    uint64_t part_size;              // Size of the part
    uint64_t start_byte;             // Start offset of the part in the file
    FILE *infile;                    // File pointer. Each part has an exclusive file pointer.
    char etag[256];                  // ETag after the part is successfully uploaded
    obs_status ret_status;           // Upload result status of the part
} UploadPartTask;
// Task queue shared by multiple threads
static UploadPartTask *g_tasks = NULL;
static int g_task_count = 0;
static int g_task_index = 0;
static pthread_mutex_t g_task_mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char **argv)
{
    // The following example shows how to concurrently upload multiple parts of a large file:
    // Multipart upload consists of three steps: 1. Initiate a multipart upload task. 2. Upload parts. 3. Complete or abort the multipart upload.
    // Call the obs_initialize method at the program entry to initialize global resources such as the network and memory.
    obs_status ret_status = obs_initialize(OBS_INIT_ALL);
    if (OBS_STATUS_OK != ret_status)
    {
        printf("obs_initialize failed(%s).\n", obs_get_status_name(ret_status));
        return -1;
    }
    obs_options options;
    // Create and initialize options, including the access domain name (host_name), access keys (access_key_id and access_key_secret), bucket name (bucket_name), and bucket storage class (storage_class).
    init_obs_options(&options);
    // Enter the endpoint corresponding to the bucket for host_name. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
    options.bucket_options.host_name = "obs.ap-southeast-1.myhuaweicloud.com";
 
    // Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
    // In this example, the AK and SK are stored in environment variables for identity authentication. Before running the code in this example, configure local environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY.
    options.bucket_options.access_key = getenv("ACCESS_KEY_ID");
    options.bucket_options.secret_access_key = getenv("SECRET_ACCESS_KEY");
    if (!options.bucket_options.access_key || !options.bucket_options.secret_access_key) {
        printf("ERROR: ACCESS_KEY_ID and SECRET_ACCESS_KEY environment variables must be set.\n");
        obs_deinitialize();
        return -1;
    }
    // Specify the bucket name, for example, example-bucket-name.
    char * bucket_name = "example-bucket-name";
    options.bucket_options.bucket_name = bucket_name;
    // Path of the local large file to be uploaded and the object name
    char *key = (argc > 1) ? argv[1] : "example_multi_part_upload_object_key";
    char *file_path = (argc > 2) ? argv[2] : "/local/path/to/largefile";
    // Obtain the file size and calculate the number of parts.
    FILE *fp = fopen(file_path, "rb");
    if (fp == NULL) {
        printf("ERROR: failed to open local file %s.\n", file_path);
        obs_deinitialize();
        return -1;
    }
    fseek(fp, 0, SEEK_END);
    uint64_t filesize = (uint64_t)ftell(fp);
    fclose(fp);
    unsigned int part_count = (unsigned int)((filesize + PART_SIZE - 1) / PART_SIZE);
    if (part_count > MAX_PARTS) {
        printf("ERROR: file too large, part count %u exceeds max %d.\n", part_count, MAX_PARTS);
        obs_deinitialize();
        return -1;
    }
    printf("file size: %lu bytes, part count: %u, part size: %d bytes\n",
           (unsigned long)filesize, part_count, PART_SIZE);
    // Initialize upload properties.
    obs_put_properties put_properties;
    init_put_properties(&put_properties);
    // Set the response callback function.
    obs_response_handler handler =
    {
        &response_properties_callback,
        &response_complete_callback
    };
    // ========== Step 1: Initiate a multipart upload task and obtain the upload ID. ==========
    printf("\n[Step 1] initiate multi part upload...\n");
    char upload_id[256] = {0};
    int upload_id_size = (int)sizeof(upload_id);
    ret_status = OBS_STATUS_BUTT;
    initiate_multi_part_upload(&options, key, upload_id_size, upload_id,
                                &put_properties, 0, &handler, &ret_status);
    if (OBS_STATUS_OK != ret_status) {
        printf("initiate multi part upload failed(%s).\n", obs_get_status_name(ret_status));
        obs_deinitialize();
        return -1;
    }
    printf("initiate multi part upload successfully. uploadId=%s\n", upload_id);
    // Construct a multipart upload task queue.
    g_tasks = (UploadPartTask *)malloc(sizeof(UploadPartTask) * part_count);
    if (g_tasks == NULL) {
        printf("ERROR: failed to allocate task memory.\n");
        abort_multi_part_upload(&options, key, upload_id, &handler, &ret_status);
        obs_deinitialize();
        return -1;
    }
    memset(g_tasks, 0, sizeof(UploadPartTask) * part_count);
    for (unsigned int i = 0; i < part_count; i++) {
        g_tasks[i].options = &options;
        g_tasks[i].key = key;
        g_tasks[i].upload_id = upload_id;
        g_tasks[i].part_number = i + 1;
        g_tasks[i].part_size = (i == part_count - 1) ? (filesize - (uint64_t)i * PART_SIZE) : PART_SIZE;
        g_tasks[i].start_byte = (uint64_t)i * PART_SIZE;
        g_tasks[i].infile = fopen(file_path, "rb");
        if (g_tasks[i].infile) {
            fseek(g_tasks[i].infile, (long)g_tasks[i].start_byte, SEEK_SET);
        }
        g_tasks[i].ret_status = OBS_STATUS_BUTT;
    }
    g_task_count = (int)part_count;
    g_task_index = 0;
    // ========== Step 2: Upload parts concurrently. ==========
    printf("\n[Step 2] upload parts concurrently (thread_num=%d)...\n", THREAD_NUM);
    pthread_t threads[THREAD_NUM];
    int thread_num = (THREAD_NUM < (int)part_count) ? THREAD_NUM : (int)part_count;
    for (int i = 0; i < thread_num; i++) {
        pthread_create(&threads[i], NULL, upload_part_worker, NULL);
    }
    for (int i = 0; i < thread_num; i++) {
        pthread_join(threads[i], NULL);
    }
    // Check the upload result of each part.
    int failed_count = 0;
    for (unsigned int i = 0; i < part_count; i++) {
        if (g_tasks[i].ret_status != OBS_STATUS_OK || g_tasks[i].etag[0] == '\0') {
            failed_count++;
        }
        if (g_tasks[i].infile) {
            fclose(g_tasks[i].infile);
            g_tasks[i].infile = NULL;
        }
    }
    if (failed_count > 0) {
        printf("upload parts failed, %d part(s) failed.\n", failed_count);
        // If any part fails to be uploaded, abort the multipart upload task. This is the abort branch of step 3.
        printf("\n[Step 3] abort multi part upload (due to part upload failure)...\n");
        ret_status = OBS_STATUS_BUTT;
        abort_multi_part_upload(&options, key, upload_id, &handler, &ret_status);
        if (OBS_STATUS_OK == ret_status) {
            printf("abort multi part upload successfully.\n");
        } else {
            printf("abort multi part upload failed(%s).\n", obs_get_status_name(ret_status));
        }
        free(g_tasks);
        obs_deinitialize();
        return -1;
    }
    // ========== Step 3: Complete the multipart upload. ==========
    printf("\n[Step 3] complete multi part upload...\n");
    obs_complete_upload_Info *upload_info = (obs_complete_upload_Info *)malloc(
        sizeof(obs_complete_upload_Info) * part_count);
    if (upload_info == NULL) {
        printf("ERROR: failed to allocate complete info memory.\n");
        abort_multi_part_upload(&options, key, upload_id, &handler, &ret_status);
        free(g_tasks);
        obs_deinitialize();
        return -1;
    }
    memset(upload_info, 0, sizeof(obs_complete_upload_Info) * part_count);
    for (unsigned int i = 0; i < part_count; i++) {
        upload_info[i].part_number = g_tasks[i].part_number;
        upload_info[i].etag = g_tasks[i].etag;
    }
    obs_complete_multi_part_upload_handler complete_handler =
    {
        {&response_properties_callback, &response_complete_callback},
        &complete_multipart_upload_callback
    };
    ret_status = OBS_STATUS_BUTT;
    complete_multi_part_upload(&options, key, upload_id, part_count, upload_info,
                                &put_properties, &complete_handler, &ret_status);
    if (OBS_STATUS_OK == ret_status) {
        printf("complete multi part upload successfully.\n");
    } else {
        printf("complete multi part upload failed(%s).\n", obs_get_status_name(ret_status));
    }
    free(upload_info);
    free(g_tasks);
    // Release the allocated global resources.
    obs_deinitialize();
    return (ret_status == OBS_STATUS_OK) ? 0 : -1;
}
// Worker thread: Obtains multipart upload tasks from the queue and performs the upload.
void *upload_part_worker(void *arg)
{
    (void)arg;
    while (1) {
        pthread_mutex_lock(&g_task_mutex);
        if (g_task_index >= g_task_count) {
            pthread_mutex_unlock(&g_task_mutex);
            break;
        }
        int idx = g_task_index++;
        pthread_mutex_unlock(&g_task_mutex);
        UploadPartTask *task = &g_tasks[idx];
        obs_upload_part_info part_info;
        memset(&part_info, 0, sizeof(obs_upload_part_info));
        part_info.part_number = task->part_number;
        part_info.upload_id = task->upload_id;
        obs_upload_handler part_handler =
        {
            {&upload_part_properties_callback, &upload_part_complete_callback},
            &upload_part_data_callback,
            NULL
        };
        obs_put_properties put_properties;
        init_put_properties(&put_properties);
        // Upload parts. (Data is read through upload_part_data_callback.)
        task->ret_status = OBS_STATUS_BUTT;
        upload_part(task->options, task->key, &part_info, task->part_size,
                    &put_properties, 0, &part_handler, task);
        if (OBS_STATUS_OK == task->ret_status) {
            printf("[part %u] upload successfully (%lu bytes)\n",
                   task->part_number, (unsigned long)task->part_size);
        } else {
            printf("[part %u] upload failed(%s)\n", task->part_number,
                   obs_get_status_name(task->ret_status));
        }
    }
    return NULL;
}
// Callback function for uploading parts. The SDK uses this callback function to read parts.
int upload_part_data_callback(int buffer_size, char *buffer, void *callback_data)
{
    UploadPartTask *task = (UploadPartTask *)callback_data;
    if (task == NULL || task->infile == NULL) {
        return 0;
    }
    // Read data from the current position of the file and fill the data in the buffer.
    int toRead = (buffer_size < (int)task->part_size) ? buffer_size : (int)task->part_size;
    size_t read = fread(buffer, 1, (size_t)toRead, task->infile);
    task->part_size -= read;
    return (int)read;
}
// Callback function for completing a multipart upload. It is used to return the assembling result.
obs_status complete_multipart_upload_callback(const char *location, const char *bucket,
                                              const char *key, const char *etag,
                                              void *callback_data)
{
    (void)callback_data;
    printf("complete result: location=%s, bucket=%s, key=%s, etag=%s\n",
           location ? location : "(null)",
           bucket ? bucket : "(null)",
           key ? key : "(null)",
           etag ? etag : "(null)");
    return OBS_STATUS_OK;
}
// The response callback function. In this callback, you can record the content of properties into callback_data (custom callback data).
obs_status response_properties_callback(const obs_response_properties *properties, void *callback_data)
{
    (void)callback_data;
    if (properties == NULL)
    {
        printf("error! obs_response_properties is null!");
        return OBS_STATUS_OK;
    }
// Print the response.
#define print_nonnull(name, field)                                 \
    do {                                                           \
        if (properties-> field) {                                  \
            printf("%s: %s\n", name, properties->field);          \
        }                                                          \
    } while (0)
    print_nonnull("request_id", request_id);
    print_nonnull("request_id2", request_id2);
    print_nonnull("content_type", content_type);
    if (properties->content_length) {
        printf("content_length: %lu\n", properties->content_length);
    }
    print_nonnull("server", server);
    print_nonnull("ETag", etag);
    print_nonnull("expiration", expiration);
    print_nonnull("website_redirect_location", website_redirect_location);
    print_nonnull("version_id", version_id);
    print_nonnull("allow_origin", allow_origin);
    print_nonnull("allow_headers", allow_headers);
    print_nonnull("max_age", max_age);
    print_nonnull("allow_methods", allow_methods);
    print_nonnull("expose_headers", expose_headers);
    print_nonnull("storage_class", storage_class);
    print_nonnull("server_side_encryption", server_side_encryption);
    print_nonnull("kms_key_id", kms_key_id);
    print_nonnull("customer_algorithm", customer_algorithm);
    print_nonnull("customer_key_md5", customer_key_md5);
    print_nonnull("bucket_location", bucket_location);
    print_nonnull("obs_version", obs_version);
    print_nonnull("restore", restore);
    print_nonnull("obs_object_type", obs_object_type);
    print_nonnull("obs_next_append_position", obs_next_append_position);
    print_nonnull("obs_head_epid", obs_head_epid);
    print_nonnull("reserved_indicator", reserved_indicator);
    int i;
    for (i = 0; i < properties->meta_data_count; i++) {
        printf("x-obs-meta-%s: %s\n", properties->meta_data[i].name,
            properties->meta_data[i].value);
    }
    return OBS_STATUS_OK;
}
// The dedicated response callback for uploading parts (callback_data is passed as UploadPartTask*). It is used to record the ETags of parts.
obs_status upload_part_properties_callback(const obs_response_properties *properties, void *callback_data)
{
    if (properties == NULL || callback_data == NULL) {
        return OBS_STATUS_OK;
    }
    UploadPartTask *task = (UploadPartTask *)callback_data;
    if (properties->etag && task->etag[0] == '\0') {
        strncpy(task->etag, properties->etag, sizeof(task->etag) - 1);
        task->etag[sizeof(task->etag) - 1] = '\0';
    }
    return OBS_STATUS_OK;
}
// The completion callback function (general, callback_data is passed as obs_status*). It is used to record the result status.
void response_complete_callback(obs_status status, const obs_error_details *error, void *callback_data)
{
    if (callback_data) {
        obs_status *ret_status = (obs_status *)callback_data;
        *ret_status = status;
    } else {
        printf("Callback_data is NULL");
    }
    if (error && error->message) {
        printf("Error Message: \n   %s\n", error->message);
    }
    if (error && error->resource) {
        printf("Error Resource: \n  %s\n", error->resource);
    }
    if (error && error->further_details) {
        printf("Error further_details: \n   %s\n", error->further_details);
    }
    if (error && error->extra_details_count) {
        int i;
        for (i = 0; i < error->extra_details_count; i++) {
            printf("Error Extra Detail(%d):\n   %s:%s\n", i, error->extra_details[i].name,
                   error->extra_details[i].value);
        }
    }
    if (error && error->error_headers_count) {
        int i;
        for (i = 0; i < error->error_headers_count; i++) {
            const char *errorHeader = error->error_headers[i];
            printf("Error Headers(%d):\n    %s\n", i, errorHeader == NULL ? "NULL Header" : errorHeader);
        }
    }
}
// The dedicated completion callback for uploading parts (callback_data is passed as UploadPartTask*). It is used to record the result status of the multipart upload.
void upload_part_complete_callback(obs_status status, const obs_error_details *error, void *callback_data)
{
    UploadPartTask *task = (UploadPartTask *)callback_data;
    if (task) {
        task->ret_status = status;
    }
    if (error && error->message) {
        printf("[part %u] Error: %s\n", task ? task->part_number : 0, error->message);
    }
}

When uploading a large file in parts, you need to use the Offset and PartSize parameters to specify the start and end positions of each part in the file.

If the concurrency value is too great, timeout may occur due to network instability. In such a case, you need to reduce that value.