Updated on 2023-11-09 GMT+08:00

Performing a File-Based Upload

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

File-based upload uses local files as the data source of objects. For parameters, see Performing a Streaming Upload. Sample code:

static void test_put_object_from_file()
{
     // Name of an object to be uploaded
    char *key = "put_file_test";
    // File to be uploaded
    char file_name[256] = "./put_file_test.txt";
    uint64_t content_length = 0;
    // Initialize option.
    obs_options option;
    init_obs_options(&option);
    option.bucket_options.host_name = "<your-endpoint>";
    option.bucket_options.bucket_name = "<Your bucketname>";

    // 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 ACCESS_KEY_ID and SECRET_ACCESS_KEY.
    // 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.
    option.bucket_options.access_key = getenv("ACCESS_KEY_ID");
    option.bucket_options.secret_access_key = getenv("SECRET_ACCESS_KEY");
    option.bucket_options.certificate_info = "<Your certificate>";
    // Initialize the properties of an object to be uploaded.
    obs_put_properties put_properties;
    init_put_properties(&put_properties);

    // Initialize the structure for storing uploaded data.
    put_file_object_callback_data data;
    memset(&data, 0, sizeof(put_file_object_callback_data));
    // Open the file and obtain the file length.
    content_length = open_file_and_get_length(file_name, &data);
    // Set callback function.
    obs_put_object_handler putobjectHandler =
    { 
        { &response_properties_callback, &put_file_complete_callback },
        &put_file_data_callback
    };

    put_object(&option, key, content_length, &put_properties, 0, &putobjectHandler, &data);
    if (OBS_STATUS_OK == data.ret_status) {
        printf("put object from file successfully. \n");
    }
    else
    {
        printf("put object failed(%s).\n",  
               obs_get_status_name(data.ret_status));
    }
}
  • The content to be uploaded cannot exceed 5 GB.
  • When uploading file streams, you must open files in rb or rb+ mode.