C++禁止覆盖同名文件

默认情况下,如果新添加文件与现有文件(Object)同名且对该文件有访问权限,则新添加的文件将覆盖原有的文件。本文介绍如何通过设置请求头x-oss-forbid-overwrite在简单上传、拷贝文件及分片上传等场景中禁止覆盖同名文件。

注意事项

  • 本文以华东1(杭州)外网Endpoint为例。如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见访问域名和数据中心

  • 本文以OSS域名新建OSSClient为例。如果您希望通过自定义域名、STS等方式新建OSSClient,请参见新建OssClient

简单上传

以下代码用于简单上传时禁止覆盖同名文件:

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

int main(void)
{
    /* 初始化OSS账号信息。*/
            
    /* 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。*/
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    /* 填写Bucket名称,例如examplebucket。*/
    std::string BucketName = "examplebucket";
    /* 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。*/
    std::string ObjectName = "exampledir/exampleobject.txt";

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

    ClientConfiguration conf;
    /* 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "test cpp sdk";

    /* 指定上传文件操作时是否覆盖同名Object。*/
    /* 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。*/
    ObjectMetaData meta;
    meta.addHeader("x-oss-forbid-overwrite", "true");

    PutObjectRequest request(BucketName, ObjectName, content, meta);

    /* 上传文件。*/
    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;
        return -1;
    }

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

拷贝文件

拷贝小文件

以下代码用于拷贝小文件时禁止覆盖同名文件:

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

int main(void)
{
    /* 初始化OSS账号信息。*/
            
    /* 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。*/
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    /* 填写源Bucket名称,例如srcexamplebucket。*/
    std::string SourceBucketName = "srcexamplebucket";
    /* 填写与源Bucket处于同一地域的目标Bucket名称,例如destbucket。*/
    std::string CopyBucketName = "destbucket";
    /* 填写源Object的完整路径,完整路径中不能包含Bucket名称,例如srcdir/scrobject.txt。*/
    std::string SourceObjectName = "srcdir/scrobject.txt";
    /* 填写目标Object的完整路径,完整路径中不能包含Bucket名称,例如destdir/destobject.txt。*/
    std::string CopyObjectName = "destdir/destobject.txt";

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

    ClientConfiguration conf;
    /* 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* 指定上传文件操作时是否覆盖同名Object。*/
    /* 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。*/
    ObjectMetaData meta;
    meta.addHeader("x-oss-forbid-overwrite", "true");

    CopyObjectRequest request(CopyBucketName, CopyObjectName, meta);
    request.setCopySource(SourceBucketName, SourceObjectName);

    /* 拷贝文件。*/
    auto outcome = client.CopyObject(request);

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

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

拷贝大文件

以下代码用于拷贝大文件时禁止覆盖同名文件:

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

int main(void)
{
    /* 初始化OSS账号信息。*/
            
    /* 填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。*/
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    /* 填写源Bucket名称,例如srcexamplebucket。*/
    std::string SourceBucketName = "srcexamplebucket";
    /* 填写与源Bucket处于同一地域的目标Bucket名称,例如destbucket。*/
    std::string CopyBucketName = "destbucket";
    /* 填写源Object的完整路径,完整路径中不能包含Bucket名称,例如srcdir/scrobject.txt。*/
    std::string SourceObjectName = "srcdir/scrobject.txt";
    /* 填写目标Object的完整路径,完整路径中不能包含Bucket名称,例如destdir/destobject.txt。*/
    std::string CopyObjectName = "destdir/destobject.txt";

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

    ClientConfiguration conf;
    /* 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    auto getObjectMetaReq = GetObjectMetaRequest(SourceBucketName, SourceObjectName);
    auto getObjectMetaResult = GetObjectMeta(getObjectMetaReq);
    if (!getObjectMetaResult.isSuccess()) {
        std::cout << "GetObjectMeta fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }
        /* 获取被拷贝文件大小。*/
    auto objectSize = getObjectMetaResult.result().ContentLength();

    /* 拷贝大文件。*/
    ObjectMetaData metaData;
    std::stringstream ssDesc;
    ssDesc << "/" << SourceBucketName << "/" << SourceObjectName;
    std::string value = ssDesc.str();
    metaData.addHeader("x-oss-copy-source", value);

    /* 指定上传文件操作时是否覆盖同名Object。*/
    /* 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。*/
    metaData.addHeader("x-oss-forbid-overwrite", "true");

    InitiateMultipartUploadRequest initUploadRequest(BucketName, ObjectName, metaData);

    /* 初始化分片拷贝事件。*/
    auto uploadIdResult = client.InitiateMultipartUpload(initUploadRequest);
    auto uploadId = uploadIdResult.result().UploadId();
    int64_t partSize = 100 * 1024;
    PartList partETagList;
    int partCount = static_cast<int>(objectSize / partSize);
    /* 计算分片个数。*/
    if (objectSize % partSize != 0) {
        partCount++;
    }

    /* 对每一个分片进行拷贝。*/
    for (int i = 1; i <= partCount; i++) {
        auto skipBytes = partSize * (i - 1);
        auto size = (partSize < objectSize - skipBytes) ? partSize : (objectSize - skipBytes);
        auto uploadPartCopyReq = UploadPartCopyRequest(CopyBucketName, CopyObjectName, SourceBucketName, SourceObjectName,uploadId, i + 1);
        uploadPartCopyReq.setCopySourceRange(skipBytes, skipBytes + size -1);
        auto uploadPartOutcome = client.UploadPartCopy(uploadPartCopyReq);
        if (uploadPartOutcome.isSuccess()) {
            Part part(i, uploadPartOutcome.result().ETag());
            partETagList.push_back(part);
        }
        else {
            std::cout << "UploadPartCopy fail" <<
            ",code:" << outcome.error().Code() <<
            ",message:" << outcome.error().Message() <<
            ",requestId:" << outcome.error().RequestId() << std::endl;
        }

    }

    /* 完成分片拷贝。*/
    CompleteMultipartUploadRequest request(CopyBucketName, CopyObjectName, partETagList, uploadId);

    /* 指定上传文件操作时是否覆盖同名Object。*/
    /* 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。*/ 
    request.MetaData().addHeader("x-oss-forbid-overwrite", "true");

    auto outcome = client.CompleteMultipartUpload(request);

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

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

分片上传

以下代码用于分片上传时禁止覆盖同名文件:

#include <alibabacloud/oss/OssClient.h>
#include <fstream>

int64_t getFileSize(const std::string& file)
{
        std::fstream f(file, std::ios::in | std::ios::binary);
    f.seekg(0, f.end);
    int64_t size = f.tellg();
    f.close();
    return size;
}

using namespace AlibabaCloud::OSS;

int main(void)
{
    /* 初始化OSS账号信息。*/
            
    /* yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。*/
    std::string Endpoint = "yourEndpoint";
    /* 填写Bucket名称,例如examplebucket。*/
    std::string BucketName = "examplebucket";
    /* 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。*/
    std::string ObjectName = "exampledir/exampleobject.txt";

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

    ClientConfiguration conf;
    /* 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* 指定上传文件操作时是否覆盖同名Object。*/
    /* 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。*/
    ObjectMetaData meta;
    meta.addHeader("x-oss-forbid-overwrite", "true");

    InitiateMultipartUploadRequest initUploadRequest(BucketName, ObjectName, meta);

    /* 初始化分片上传事件。*/
    auto uploadIdResult = client.InitiateMultipartUpload(initUploadRequest);
    auto uploadId = uploadIdResult.result().UploadId();
    std::string fileToUpload = "yourLocalFilename";
    int64_t partSize = 100 * 1024;
    PartList partETagList;
    auto fileSize = getFileSize(fileToUpload);
    int partCount = static_cast<int>(fileSize / partSize);
    /* 计算分片个数。*/
    if (fileSize % partSize != 0) {
        partCount++;
    }

    /* 对每一个分片进行上传。*/
    for (int i = 1; i <= partCount; i++) {
        auto skipBytes = partSize * (i - 1);
        auto size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
        std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>(fileToUpload, std::ios::in|std::ios::binary);
        content->seekg(skipBytes, std::ios::beg);

        UploadPartRequest uploadPartRequest(BucketName, ObjectName, content);
        uploadPartRequest.setContentLength(size);
        uploadPartRequest.setUploadId(uploadId);
        uploadPartRequest.setPartNumber(i);
        auto uploadPartOutcome = client.UploadPart(uploadPartRequest);
        if (uploadPartOutcome.isSuccess()) {
                Part part(i, uploadPartOutcome.result().ETag());
                partETagList.push_back(part);
        }
        else {
                std::cout << "uploadPart fail" <<
            ",code:" << uploadPartOutcome.error().Code() <<
            ",message:" << uploadPartOutcome.error().Message() <<
            ",requestId:" << uploadPartOutcome.error().RequestId() << std::endl;
        }

    }

    /* 完成分片上传。*/
    CompleteMultipartUploadRequest request(BucketName, ObjectName);
    request.setUploadId(uploadId);
    request.setPartList(partETagList);

    /* 指定上传文件操作时是否覆盖同名Object。*/
    /* 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。*/
    /* 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。*/ 
    request.MetaData().addHeader("x-oss-forbid-overwrite", "true");
    auto outcome = client.CompleteMultipartUpload(request);

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

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

相关文档