上传对象

对象是存储数据的基本单元。对象由元信息(Object Meta),用户数据(Data)和文件名(Key)组成。对象由桶内部唯一的Key来标识。本文介绍如何上传对象。

接口定义:

void S3_put_object(const S3BucketContext *bucketContext, const char *key,
                   uint64_t contentLength,
                   const S3PutProperties *putProperties,
                   S3RequestContext *requestContext,
                   int timeoutMs,
                   const S3PutObjectHandler *handler, void *callbackData);

参数:

参数名 类型 说明
bucketContext const S3BucketContext * 包含bucket及相关的请求参数
key const char * 将要上传的对象的文件名
contentLength uint64_t 将要上传的对象的字节数
putProperties const S3PutProperties * 请求消息头,可选地提供了附加的属性以应用于要上传的对象
requestContext S3RequestContext * 请求参数,如果为NULL,则立即同步执行请求
timeoutMs int 如果非0,则是以毫秒为单位的请求超时时间
handler const S3ResponseHandler * 回调函数
callbackData void * 回调数据

代码示例:

#include <sys/stat.h>
#include <unistd.h>

void put_object()
{
    put_object_callback_data data;
    struct stat statbuf;
    if (stat(test_file, &statbuf) == -1)
    {
        fprintf(stderr, "\nERROR: Failed to stat file %s: ", test_file);
        perror(0);
        exit(-1);
    }

    int contentLength = statbuf.st_size;
    data.contentLength = contentLength;

    if (!(data.infile = fopen(test_file, "r")))
    {
        fprintf(stderr, "\nERROR: Failed to open input file %s: ", test_file);
        perror(0);
        exit(-1);
    }

    S3ResponseHandler responseHandler =
        {
            &responsePropertiesCallback, &responseCompleteCallback};

    S3PutObjectHandler putObjectHandler =
        {
            responseHandler,
            &putObjectDataCallback};

    do
    {
        S3_put_object(&bucketContext, test_key, contentLength, NULL, NULL, 0, &putObjectHandler, &data);
    } while (S3_status_is_retryable(statusG) && should_retry());

    fclose(data.infile);

    if (statusG != S3StatusOK)
    {
        printError();
    }
    else if (data.contentLength)
    {
        fprintf(stderr, "\nERROR: Failed to read remaining %llu bytes from "
                        "input\n",
                (unsigned long long)data.contentLength);
    }
}