Todos os produtos
Search
Central de documentação

Object Storage Service:Copy a file (Android SDK)

Última atualização: Sep 22, 2026

Copie objetos dentro de um bucket ou entre buckets na mesma região.

Precauções

  • Para copiar um arquivo, você precisa ter permissões de leitura no arquivo source e permissões de leitura e escrita no bucket de destino.

  • Não há suporte para cópia entre regiões. Por exemplo, não é possível copiar um arquivo de um bucket na região China (Hangzhou) para um bucket na região China (Qingdao).

  • O tamanho do arquivo a ser copiado não pode exceder 1 GB.

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

Permissões

Por padrão, uma conta Alibaba Cloud possui permissões completas. Usuários RAM ou funções RAM vinculados a uma conta Alibaba Cloud não possuem nenhuma permissão por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder permissões de operação por meio de RAM policies ou Bucket Policy.

API

Action

Descrição

CopyObject

oss:GetObject

Copia objetos dentro de um bucket ou entre buckets na mesma região.

oss:PutObject

oss:GetObjectVersion

Ao especificar a versão do objeto source por meio de versionId, essa permissão também é necessária.

oss:GetObjectTagging

Ao copiar tags de objetos por meio de x-oss-tagging, essas permissões são necessárias.

oss:PutObjectTagging

oss:GetObjectVersionTagging

Ao especificar as tags de uma versão específica do objeto source por meio de versionId, essa permissão também é necessária.

kms:GenerateDataKey

Ao copiar um objeto cujos metadados de destino contêm X-Oss-Server-Side-Encryption: KMS, essas duas permissões são necessárias.

kms:Decrypt

Código de exemplo

O código a seguir mostra como copiar um arquivo:

// Specify the name of the source bucket.
String srcBucketName = "src-bucket";
// Specify the full path of the object in the source bucket.
String srcObjectKey = "dir1/source-object.txt";
// Specify the name of the destination bucket, which must be in the same region as the source bucket.
String destBucketName = "dest-bucket";
// Specify the full path of the object in the destination bucket.
String destObjectKey = "dir2/destination-object.txt";
// Create a copy request.
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcObjectKey, destBucketName, destObjectKey);

// ObjectMetadata objectMetadata = new ObjectMetadata();
// Set the access control list (ACL) of the object. In this example, the ACL is set to private.
// objectMetadata.setHeader("x-oss-object-acl", "private");
// Set the storage class of the object. In this example, the storage class is set to Standard.
// objectMetadata.setHeader("x-oss-storage-class", "Standard");
// Specify whether to overwrite an existing object that has the same name in the destination bucket. In this example, the value is set to true, which indicates that the existing object cannot be overwritten.
// objectMetadata.setHeader("x-oss-forbid-overwrite", "true");
// The copy operation is performed only if the ETag of the source object matches the specified ETag.
// objectMetadata.setHeader("x-oss-copy-source-if-match", "5B3C1A2E053D763E1B002CC607C5****");
// Specify the source address for the copy operation.
// objectMetadata.setHeader("x-oss-copy-source", "/example-bucket/recode-test.txt");
// The copy operation is performed only if the ETag of the source object does not match the specified ETag.
// objectMetadata.setHeader("x-oss-copy-source-if-none-match", "5B3C1A2E053D763E1B002CC607C5****");
// The copy operation is performed only if the actual modification time of the object is earlier than or the same as the specified time.
// objectMetadata.setHeader("x-oss-copy-source-if-unmodified-since", "2021-12-09T07:01:56.000Z");
// The copy operation is performed only if the source object was modified after the specified time.
// objectMetadata.setHeader("x-oss-copy-source-if-modified-since", "2021-12-09T07:01:56.000Z");
// Specify how to configure the metadata of the destination object. In this example, the value is set to COPY, which indicates that the metadata of the source object is copied to the destination object.
// objectMetadata.setHeader("x-oss-metadata-directive", "COPY");
// Specify the server-side encryption algorithm that OSS uses to create the destination object.
// objectMetadata.setHeader("x-oss-server-side-encryption", "SSE-KMS");
// The customer master key (CMK) managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
// objectMetadata.setHeader("x-oss-server-side-encryption-key-id", "9468da86-3509-4f8d-a61e-6eab1eac****");
// Specify the tags of the object. You can specify multiple tags at the same time.
// objectMetadata.setHeader("x-oss-tagging", "a:1");
// Specify how to configure the tags of the destination object. In this example, the value is set to COPY, which indicates that the tags of the source object are copied to the destination object.
// objectMetadata.setHeader("x-oss-tagging-directive", "COPY");

// Perform an asynchronous copy.
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 exception.
            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());
        }
    }
});

Referências