Todos os produtos
Search
Central de documentação

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

Última atualização: Jul 03, 2026

Por padrão, fazer upload de um objeto com o mesmo nome de um objeto existente substitui este último, desde que você tenha as permissões de acesso necessárias. Este tópico descreve como definir o cabeçalho de solicitação x-oss-forbid-overwrite para evitar a substituição de objetos em cenários como uploads simples, cópias de objetos e uploads multipart.

Observações de uso

  • Antes de executar o código de exemplo deste tópico, crie uma instância OSSClient usando métodos como nome de domínio personalizado ou Security Token Service (STS). Para mais informações, consulte Inicialização (Android SDK).

Upload simples

O código de exemplo a seguir mostra como impedir a substituição de objetos existentes por outros com o mesmo nome durante um upload simples:

// 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());
        }
    }
});

Cópia de arquivos

O exemplo de código abaixo ilustra como evitar a substituição de um objeto existente em um bucket por outro com o mesmo nome durante uma tarefa de cópia:

// 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());
        }
    }
});

Upload multipart

Para impedir a substituição de um objeto existente ao fazer upload de um arquivo com o mesmo nome via upload multipart, utilize o seguinte código de exemplo:

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

Referências

  • Para mais informações sobre a operação de API usada para realizar uploads simples, consulte PutObject.

  • Para detalhes sobre a operação de API destinada à cópia de objetos, consulte CopyObject.

  • Para saber mais sobre como inicializar uma instância OSSClient, consulte Inicialização.

  • O upload multipart envolve três operações de API. Para mais informações sobre essas operações, consulte os seguintes tópicos:

    • Para uma descrição da operação de API que inicializa um upload multipart, consulte InitiateMultipartUpload.

    • Para mais informações sobre a operação de API referente ao upload de uma parte (Part) de um upload multipart, consulte UploadPart.

    • Para detalhes sobre a operação de API que conclui um upload multipart, consulte CompleteMultipartUpload.