All Products
Search
Document Center

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

Last Updated:Mar 20, 2026

By default, if you have the required access permissions, uploading an object with the same name as an existing object overwrites it. To prevent this, set the x-oss-forbid-overwrite request header to true. The header is supported for simple uploads, object copies, and multipart uploads.

Prerequisites

Before you begin, ensure that you have:

  • An initialized OSSClient instance. For setup instructions, see Initialization

How x-oss-forbid-overwrite works

Set this header on ObjectMetadata before submitting the request:

ValueBehavior
Not set (default)Existing objects with the same name are overwritten
falseExisting objects with the same name are overwritten
trueThe operation fails if an object with the same name exists

Simple upload

// 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";

PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, localFile);
ObjectMetadata metadata = new ObjectMetadata();

// Specify whether to overwrite an object with the same name.
// 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) {
        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());
        }
    }
});

Object copy

// Enter the source bucket name.
String srcBucketName = "srcbucket";
// Enter the full path of the source object.
String srcObjectKey = "dir1/srcobject.txt";
// Enter the destination bucket name.
String destBucketName = "destbucket";
// Enter the full path of the destination object.
String destObjectKey = "dir2/destobject.txt";

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.
// 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);

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) {
        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

A multipart upload involves three API operations: InitiateMultipartUpload, UploadPart, and CompleteMultipartUpload. Set x-oss-forbid-overwrite at both the InitiateMultipartUpload and CompleteMultipartUpload steps.

// 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 upload ID uniquely identifies this multipart upload. Use it to upload parts, cancel, or query the upload.
String uploadId = initResult.getUploadId();

// Set the size of each part in bytes. The value must be between 100 KB and 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);
    // Part numbers start from 1. The value must be between 1 and 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);

What's next