All Products
Search
Document Center

Object Storage Service:Prevent objects with the same name from being overwritten (Android SDK)

Last Updated:Nov 29, 2025

By default, uploading an object with the same name as an existing object overwrites the existing object if you have the required access permissions. This topic describes how to set the x-oss-forbid-overwrite request header to prevent objects from being overwritten in scenarios such as simple uploads, object copies, and multipart uploads.

Usage notes

  • Before you run the sample code in this topic, you must create an OSSClient instance by using methods such as using a custom domain name or Security Token Service (STS). For more information, see Initialization.

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:

// Enter the bucket name. Example: examplebucket. For more information about bucket naming conventions, see Buckets.
String bucketName = "examplebucket";
// Enter the full path of the object. Do not include the bucket name. Example: exampledir/exampleobject.txt. For more information about object naming conventions, see Objects.
String objectKey = "exampledir/exampleobject.txt";
// Enter the full path of the local file to upload.
String localFile = "/storage/emulated/0/oss/examplefile.txt";
// Create an upload request.
PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, localFile);
ObjectMetadata metadata = new ObjectMetadata();

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

OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");
        Log.d("ETag", result.getETag());
        Log.d("RequestId", result.getRequestId());
    }

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // The request failed.
        if (clientExcepion != null) {
            // A client exception occurred, such as a network error.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // A server-side exception occurred.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Copying files

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

// Enter the source bucket name.
String srcBucketName = "srcbucket";
// Enter the full path of the source object in the bucket.
String srcObjectKey = "dir1/srcobject.txt";
// Enter the destination bucket name.
String destBucketName = "destbucket";
// Enter the full path of the destination object in the bucket.
String destObjectKey = "dir2/destobject.txt";
// Create a copy request.
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcObjectKey, destBucketName, destObjectKey);

ObjectMetadata metadata = new ObjectMetadata();

// Specify whether to overwrite an object with the same name during the copy operation.
// If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name exists, the program reports an error.
metadata.setHeader("x-oss-forbid-overwrite", "true");
copyObjectRequest.setNewObjectMetadata(metadata);

// Copy the object asynchronously.
OSSAsyncTask copyTask = oss.asyncCopyObject(copyObjectRequest, new OSSCompletedCallback<CopyObjectRequest, CopyObjectResult>() {
    @Override
    public void onSuccess(CopyObjectRequest request, CopyObjectResult result) {
        Log.d("copyObject", "copy success!");
    }

    @Override
    public void onFailure(CopyObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // The request failed.
        if (clientExcepion != null) {
            // A client exception occurred, such as a network error.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // A service exception occurred.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

Multipart Upload

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

// Enter the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Enter the full path of the object. Do not include the bucket name. Example: exampledir/exampleobject.txt.
String objectKey = "exampledir/exampleobject.txt";
// Enter the full path of the local file to upload.
String localFile = "/storage/emulated/0/oss/examplefile.txt";

// Initialize the multipart upload.
InitiateMultipartUploadRequest init = new InitiateMultipartUploadRequest(bucketName, objectKey);
ObjectMetadata metadata = new ObjectMetadata();
// Specify whether to overwrite an object with the same name during the upload.
// If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name exists, the program reports an error.
metadata.setHeader("x-oss-forbid-overwrite", "true");
init.setMetadata(metadata);

InitiateMultipartUploadResult initResult = oss.initMultipartUpload(init);
// The uploadId is returned. The uploadId is the unique identifier for the multipart upload event. You can use this uploadId to perform related operations, such as canceling or querying the multipart upload.
String uploadId = initResult.getUploadId();

// Set the size of a single part in bytes. The value must be in the range of 100 KB to 5 GB.
int partCount = 100 * 1024;
// Upload parts.
List<PartETag> partETags = new ArrayList<PartETag>();
for (int i = 1; i < 5; i++) {
    byte[] data = new byte[partCount];

    RandomAccessFile raf = new RandomAccessFile(localFile, "r");
    long skip = (i-1) * partCount;
    raf.seek(skip);
    raf.readFully(data, 0, partCount);

    UploadPartRequest uploadPart = new UploadPartRequest();
    uploadPart.setBucketName(bucketName);
    uploadPart.setObjectKey(objectKey);
    uploadPart.setUploadId(uploadId);
    // Set the part number. Part numbers start from 1. Each uploaded part has a part number. The value must be in the range of 1 to 10,000.
    uploadPart.setPartNumber(i);
    uploadPart.setPartContent(data);
    try {
        UploadPartResult result = oss.uploadPart(uploadPart);
        PartETag partETag = new PartETag(uploadPart.getPartNumber(), result.getETag());
        partETags.add(partETag);
    } catch (ServiceException serviceException) {
        OSSLog.logError(serviceException.getErrorCode());
    }
}
Collections.sort(partETags, new Comparator<PartETag>() {
    @Override
    public int compare(PartETag lhs, PartETag rhs) {
        if (lhs.getPartNumber() < rhs.getPartNumber()) {
            return -1;
        } else if (lhs.getPartNumber() > rhs.getPartNumber()) {
            return 1;
        } else {
            return 0;
        }
    }
});

// Complete the multipart upload.
CompleteMultipartUploadRequest complete = new CompleteMultipartUploadRequest(bucketName, objectKey, uploadId, partETags);
metadata = new ObjectMetadata();
// Specify whether to overwrite an object with the same name when you complete the upload.
// If you do not specify x-oss-forbid-overwrite, an object with the same name is overwritten by default.
// If you set x-oss-forbid-overwrite to false, an object with the same name is overwritten.
// If you set x-oss-forbid-overwrite to true, an object with the same name is not overwritten. If an object with the same name exists, the program reports an error.
metadata.setHeader("x-oss-forbid-overwrite", "true");
complete.setMetadata(metadata);
CompleteMultipartUploadResult completeResult = oss.completeMultipartUpload(complete);           

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 how to initialize an OSSClient instance, see Initialization.

  • A multipart upload involves three API operations. For more information about the operations, see the following topics:

    • For a description of the API operation to initialize a multipart upload, see InitiateMultipartUpload.

    • For more information about the API operation for uploading a Part of a multipart upload, see UploadPart.

    • For more information about the API operation to complete a multipart upload, see CompleteMultipartUpload.