Todos os produtos
Search
Central de documentação

Object Storage Service:Impedir a substituição de objetos com o mesmo nome (Android SDK)

Última atualização: Sep 22, 2026

Por padrão, se você tiver as permissões de acesso necessárias, o upload de um objeto com o mesmo nome de um existente substitui este último. Este tópico descreve como definir o cabeçalho de requisição x-oss-forbid-overwrite para impedir que objetos sejam substituídos em cenários como uploads simples, cópias de objetos e uploads multipart.

Notas de uso

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

Upload simples

Use o exemplo de código a seguir para 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

Use o exemplo de código a seguir para impedir que um objeto existente em um bucket seja substituído por outro com o mesmo nome durante uma tarefa de cópia de objetos:

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

Use o exemplo de código a seguir para impedir a substituição de um objeto existente ao usar o upload multipart para enviar um objeto com o mesmo nome:

// 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 que você pode chamar para realizar um upload simples, consulte PutObject.

  • Para mais informações sobre a operação de API que você pode chamar para copiar um objeto, consulte CopyObject.

  • Para mais informações sobre como inicializar uma instância OSSClient, consulte Initialization.

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

    • Para obter a descrição da operação de API para inicializar um upload multipart, consulte InitiateMultipartUpload.

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

    • Para mais informações sobre a operação de API para concluir um upload multipart, consulte CompleteMultipartUpload.