All Products
Search
Document Center

Object Storage Service:Prevent objects from being overwritten by objects that have the same names

Last Updated:Oct 20, 2023

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 objects from being overwritten by objects with the same names when you copy objects or perform simple upload or multipart upload in Object Storage Service (OSS).

Usage notes

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

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

Prevent overwrites in a simple upload task

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

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

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    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";

    /* Specify whether to overwrite the existing object that has the same name. */
    /* By default, if x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to false, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to true, an existing object that has the same name is not overwritten. If an existing object has the same name as the object that you want to upload, an error is reported. */
    ObjectMetaData meta;
    meta.addHeader("x-oss-forbid-overwrite", "true");

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

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

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

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

Prevent overwrites in an object copy task

Prevent overwrites in a small object copy task

The following sample code provides an example on how to copy a small object without overwriting the existing object that has the same name:

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

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    /* Specify the name of the source bucket. Example: srcexamplebucket. */
    std::string SourceBucketName = "srcexamplebucket";
    /* Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. Example: destbucket. */
    std::string CopyBucketName = "destbucket";
    /* Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcdir/scrobject.txt. */
    std::string SourceObjectName = "srcdir/scrobject.txt";
    /* Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destdir/destobject.txt. */
    std::string CopyObjectName = "destdir/destobject.txt";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

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

    /* Specify whether to overwrite the existing object that has the same name. */
    /* By default, if x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to false, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to true, an existing object that has the same name is not overwritten. If an existing object has the same name as the object that you want to upload, an error is reported. */
    ObjectMetaData meta;
    meta.addHeader("x-oss-forbid-overwrite", "true");

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

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

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

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

Prevent overwrites in a large object copy task

The following sample code provides an example on how to prevent an existing object from being overwritten by a large object that has the same name when you copy the large object:

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

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    /* Specify the name of the source bucket. Example: srcexamplebucket. */
    std::string SourceBucketName = "srcexamplebucket";
    /* Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. Example: destbucket. */
    std::string CopyBucketName = "destbucket";
    /* Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcdir/scrobject.txt. */
    std::string SourceObjectName = "srcdir/scrobject.txt";
    /* Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destdir/destobject.txt. */
    std::string CopyObjectName = "destdir/destobject.txt";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    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;
    }
        /* Query the size of the object that you want to copy. */
    auto objectSize = getObjectMetaResult.result().ContentLength();

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

    /* Specify whether to overwrite the existing object that has the same name. */
    /* By default, if x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to false, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to true, an existing object that has the same name is not overwritten. If an existing object has the same name as the object that you want to upload, an error is reported. */
    metaData.addHeader("x-oss-forbid-overwrite", "true");

    InitiateMultipartUploadRequest initUploadRequest(BucketName, ObjectName, metaData);

    /* Initialize a multipart copy task. */
    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 task. */
    CompleteMultipartUploadRequest request(CopyBucketName, CopyObjectName, partETagList, uploadId);

    /* Specify whether to overwrite the existing object that has the same name. */
    /* By default, if x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to false, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to true, an existing object that has the same name is not overwritten. If an existing object has the same name as the object that you want to upload, an error is reported. */ 
    request.MetaData().addHeader("x-oss-forbid-overwrite", "true");

    auto outcome = client.CompleteMultipartUpload(request);

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

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

Prevent overwrites in a multipart upload task

The following sample code provides an example on how to prevent objects from being overwritten when you use multipart upload to upload objects with the same names:

#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 information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

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

    /* Specify whether to overwrite the existing object that has the same name. */
    /* By default, if x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to false, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to true, an existing object that has the same name is not overwritten. If an existing object has the same name as the object that you want to upload, an error is reported. */
    ObjectMetaData meta;
    meta.addHeader("x-oss-forbid-overwrite", "true");

    InitiateMultipartUploadRequest initUploadRequest(BucketName, ObjectName, meta);

    /* Initialize a multipart upload task. */
    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 task. */
    CompleteMultipartUploadRequest request(BucketName, ObjectName);
    request.setUploadId(uploadId);
    request.setPartList(partETagList);

    /* Specify whether to overwrite the existing object that has the same name. */
    /* By default, if x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to false, an existing object that has the same name is overwritten. */
    /* If x-oss-forbid-overwrite is set to true, an existing object that has the same name is not overwritten. If an existing object has the same name as the object that you want to upload, an error is reported. */ 
    request.MetaData().addHeader("x-oss-forbid-overwrite", "true");
    auto outcome = client.CompleteMultipartUpload(request);

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

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

References

  • For more information about the API operation that you can call to perform simple upload, see PutObject.

  • For more information about the API operation that you can call to copy an object, see CopyObject.

  • For more information about the API operations that you can call to perform multipart upload, see InitiateMultipartUpload and CompleteMultipartUpload.