All Products
Search
Document Center

Object Storage Service:Prevent overwriting files with the same name (C++ SDK)

Last Updated:Nov 29, 2025

By default, if you upload an object that has the same name as an existing object, the existing object is overwritten by the uploaded object. This topic describes how to configure the x-oss-forbid-overwrite request header to prevent existing objects from being overwritten by objects with the same names when you copy objects or perform simple upload or multipart upload.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

Simple upload

The following sample code provides an example on how to prevent existing objects from being overwritten by objects that have the same names when you perform simple upload:

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

int main(void)
{
    /* Initialize OSS account information. */
            
     /* Set yourEndpoint to the endpoint of the region where the bucket is located. For the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "test cpp sdk";

    /* Specify whether to overwrite an object that has the same name during the upload. */
    /* If you do not specify x-oss-forbid-overwrite, the object with the same name is overwritten by default. */
    /* If you set x-oss-forbid-overwrite to false, the object with the same name is overwritten. */
    /* If you set x-oss-forbid-overwrite to true, the object with the same name is not overwritten. If an object with the same name exists, the program reports an error. */
    ObjectMetaData meta;
    meta.addHeader("x-oss-forbid-overwrite", "true");

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

    /* Upload the file. */
    auto outcome = client.PutObject(request);

    if (!outcome.isSuccess()) {
            /* Handle the exception. */
            std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Copy files

Copy a small file

The following code shows how to prevent overwriting a file with the same name when you copy a small file:

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

int main(void)
{
    /* Initialize OSS account information. */
            
     /* Set yourEndpoint to the endpoint of the region where the bucket is located. For the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the source bucket name, for example, srcexamplebucket. */
    std::string SourceBucketName = "srcexamplebucket";
    /* Specify the name of the destination bucket that is in the same region as the source bucket, for example, destbucket. */
    std::string CopyBucketName = "destbucket";
    /* Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt. */
    std::string SourceObjectName = "srcdir/scrobject.txt";
    /* Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt. */
    std::string CopyObjectName = "destdir/destobject.txt";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Specify whether to overwrite an object that has the same name during the upload. */
    /* If you do not specify x-oss-forbid-overwrite, the object with the same name is overwritten by default. */
    /* If you set x-oss-forbid-overwrite to false, the object with the same name is overwritten. */
    /* If you set x-oss-forbid-overwrite to true, the object with the same name is not overwritten. If an object with the same name exists, the program reports an error. */
    ObjectMetaData meta;
    meta.addHeader("x-oss-forbid-overwrite", "true");

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

    /* Copy the file. */
    auto outcome = client.CopyObject(request);

    if (!outcome.isSuccess()) {
            /* Handle the exception. */
            std::cout << "CopyObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Copy a large file

The following code shows how to prevent overwriting a file with the same name when you copy a large file:

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

int main(void)
{
    /* Initialize OSS account information. */
            
     /* Set yourEndpoint to the endpoint of the region where the bucket is located. For the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the source bucket name, for example, srcexamplebucket. */
    std::string SourceBucketName = "srcexamplebucket";
    /* Specify the name of the destination bucket that is in the same region as the source bucket, for example, destbucket. */
    std::string CopyBucketName = "destbucket";
    /* Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt. */
    std::string SourceObjectName = "srcdir/scrobject.txt";
    /* Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt. */
    std::string CopyObjectName = "destdir/destobject.txt";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    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;
    }
        /* Get the size of the file to be copied. */
    auto objectSize = getObjectMetaResult.result().ContentLength();

    /* Copy the large file. */
    ObjectMetaData metaData;
    std::stringstream ssDesc;
    ssDesc << "/" << SourceBucketName << "/" << SourceObjectName;
    std::string value = ssDesc.str();
    metaData.addHeader("x-oss-copy-source", value);

    /* Specify whether to overwrite an object that has the same name during the upload. */
    /* If you do not specify x-oss-forbid-overwrite, the object with the same name is overwritten by default. */
    /* If you set x-oss-forbid-overwrite to false, the object with the same name is overwritten. */
    /* If you set x-oss-forbid-overwrite to true, the object with the same name is not overwritten. If an object with the same name exists, the program reports an error. */
    metaData.addHeader("x-oss-forbid-overwrite", "true");

    InitiateMultipartUploadRequest initUploadRequest(BucketName, ObjectName, metaData);

    /* Initialize the multipart copy event. */
    auto uploadIdResult = client.InitiateMultipartUpload(initUploadRequest);
    auto uploadId = uploadIdResult.result().UploadId();
    int64_t partSize = 100 * 1024;
    PartList partETagList;
    int partCount = static_cast<int>(objectSize / partSize);
    /* Calculate the number of parts. */
    if (objectSize % partSize != 0) {
        partCount++;
    }

    /* Copy each part. */
    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;
        }

    }

    /* Complete the multipart copy. */
    CompleteMultipartUploadRequest request(CopyBucketName, CopyObjectName, partETagList, uploadId);

    /* Specify whether to overwrite an object that has the same name during the upload. */
    /* If you do not specify x-oss-forbid-overwrite, the object with the same name is overwritten by default. */
    /* If you set x-oss-forbid-overwrite to false, the object with the same name is overwritten. */
    /* If you set x-oss-forbid-overwrite to true, the object with the same name is not overwritten. If an object with the same name exists, the program reports an error. */ 
    request.MetaData().addHeader("x-oss-forbid-overwrite", "true");

    auto outcome = client.CompleteMultipartUpload(request);

    if (!outcome.isSuccess()) {
        /* Handle the exception. */
        std::cout << "CompleteMultipartUpload fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Multipart upload

The following sample code provides an example on how to prevent an existing object from being overwritten by an object with the same name when you use multipart upload to upload the object:

#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)
{
    /* Initialize OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* Specify whether to overwrite an object that has the same name during the upload. */
    /* If you do not specify x-oss-forbid-overwrite, the object with the same name is overwritten by default. */
    /* If you set x-oss-forbid-overwrite to false, the object with the same name is overwritten. */
    /* If you set x-oss-forbid-overwrite to true, the object with the same name is not overwritten. If an object with the same name exists, the program reports an error. */
    ObjectMetaData meta;
    meta.addHeader("x-oss-forbid-overwrite", "true");

    InitiateMultipartUploadRequest initUploadRequest(BucketName, ObjectName, meta);

    /* Initialize the multipart upload event. */
    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);
    /* Calculate the number of parts. */
    if (fileSize % partSize != 0) {
        partCount++;
    }

    /* Upload each part. */
    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;
        }

    }

    /* Complete the multipart upload. */
    CompleteMultipartUploadRequest request(BucketName, ObjectName);
    request.setUploadId(uploadId);
    request.setPartList(partETagList);

    /* Specify whether to overwrite an object that has the same name during the upload. */
    /* If you do not specify x-oss-forbid-overwrite, the object with the same name is overwritten by default. */
    /* If you set x-oss-forbid-overwrite to false, the object with the same name is overwritten. */
    /* If you set x-oss-forbid-overwrite to true, the object with the same name is not overwritten. If an object with the same name exists, the program reports an error. */ 
    request.MetaData().addHeader("x-oss-forbid-overwrite", "true");
    auto outcome = client.CompleteMultipartUpload(request);

    if (!outcome.isSuccess()) {
            /* Handle the exception. */
            std::cout << "CompleteMultipartUpload fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

      /* Release network resources. */
    ShutdownSdk();
    return 0;
}

References