下载对象

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

接口定义:

void S3_get_object(const S3BucketContext *bucketContext, const char *key,
                   const S3GetConditions *getConditions,
                   uint64_t startByte, uint64_t byteCount,
                   S3RequestContext *requestContext,
                   int timeoutMs,
                   const S3GetObjectHandler *handler, void *callbackData);

参数:

参数名 类型 说明
bucketContext const S3BucketContext * 包含bucket及相关的请求参数
key const char * 要获取的对象的文件名
getConditions const S3GetConditions * 如果非NULL,表示请求成功必须满足的条件
startByte uint64_t 要返回的内容的起始字节
byteCount uint64_t 要返回的字节数,值为0表示返回对象的全部内容
requestContext S3RequestContext * 请求参数,如果为NULL,则立即同步执行请求
timeoutMs int 如果非0,则是以毫秒为单位的请求超时时间
handler const S3ResponseHandler * 回调函数
callbackData void * 回调数据

代码示例:

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

void get_object(const char *filename)
{
    S3ResponseHandler responseHandler =
        {
            &responsePropertiesCallback, &responseCompleteCallback};

    S3GetObjectHandler getObjectHandler =
        {
            responseHandler,
            &getObjectDataCallback};

    FILE *outfile;
    struct stat buf;
    if (stat(filename, &buf) == -1)
    {
        outfile = fopen(filename, "w");
    }
    else
    {
        // Open in r+ so that we don't truncate the file, just in case
        // there is an error and we write no bytes, we leave the file
        // unmodified
        outfile = fopen(filename, "r+");
    }

    if (!outfile)
    {
        fprintf(stderr, "\nERROR: Failed to open output file %s: ",
                filename);
        perror(0);
        exit(-1);
    }
    do
    {
        S3_get_object(&bucketContext, test_key, NULL, 0, 0, NULL, 0, &getObjectHandler, outfile);
    } while (S3_status_is_retryable(statusG) && should_retry());

    if (statusG != S3StatusOK)
    {
        printError();
    }

    fclose(outfile);
}