OSS提供基于MD5和CRC64的数据校验,确保上传、下载和拷贝文件过程中的数据完整性。

MD5校验

如果上传文件时设置了Content-MD5,OSS会根据接收的内容计算MD5。OSS计算的MD5值和上传提供的MD5值不一致时,则返回InvalidDigest异常,从而保证数据的完整性。返回InvalidDigest异常后,您需要重新上传文件。

以下代码用于上传文件时进行MD5校验:

#include <alibabacloud/oss/OssClient.h>
#include "../src/utils/Utils.h"
using namespace AlibabaCloud::OSS;

int main(void)
{
    /*初始化OSS账号信息*/
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    std::string Endpoint = "yourEndpoint";
    std::string BucketName = "yourBucketName";
    std::string ObjectName = "yourObjectName";

    /*初始化网络等资源*/
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "test cpp sdk";
    PutObjectRequest request(BucketName, ObjectName, content);

    /*设置MD5校验*/
    std::string contentMd5 = ComputeContentMD5(*content);
    request.setContentMd5(contentMd5);

    /*上传文件*/
    auto outcome = client.PutObject(request);

    if (!outcome.isSuccess()) {
        /*异常处理*/
        std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

    /*释放网络等资源*/
    ShutdownSdk();
    return 0;
}
说明 putObject、getObject、appendObject、postObject、uploadPart支持MD5校验。

CRC64校验

上传、下载和拷贝文件时默认开启CRC数据校验,确保数据的完整性。

说明
  • putObject、getObject、appendObject、uploadPart支持CRC64校验。上传时默认开启CRC校验,如果客户端计算的CRC值与服务端返回的CRC值不一致, 则会返回错误。
  • 范围下载不支持CRC64校验。
  • CRC64校验会占用一定的CPU,对上传、下载速度均会有影响。

以下代码用于下载文件时进行CRC64数据完整性校验:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /*初始化OSS账号信息*/
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    std::string Endpoint = "yourEndpoint";
    std::string BucketName = "yourBucketName";
    std::string ObjectName = "yourObjectName";

    /*初始化网络等资源*/
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /*获取文件到本地内存*/
    GetObjectRequest request(BucketName, ObjectName);
    /*C++ SDK默认开启CRC64校验*/
    /*CRC64校验失败会报错Crc64 validation failed。*/    
    auto outcome = client.GetObject(request);
    if (outcome.isSuccess()) {    
        std::cout << "getObjectToBuffer" << "server crc:" << outcome.result().Metadata().HttpMetaData().at("x-oss-hash-crc64ecma-by-client") << std::endl; 
    }
    else {
        /*异常处理*/
        std::cout << "getObjectToBuffer fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

    /*释放网络等资源*/
    ShutdownSdk();
    return 0;
}