Todos os produtos
Search
Central de documentação

Object Storage Service:Copiar um arquivo (Android SDK)

Última atualização: Jul 03, 2026

Copie objetos dentro do mesmo bucket ou entre buckets na mesma região.

Precauções

  • Para copiar um arquivo, são necessárias permissões de leitura no arquivo de origem e de leitura e gravação 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 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).

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não possuem permissões iniciais. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de políticas RAM ou Bucket Policy.

API

Ação

Descrição

CopyObject

oss:GetObject

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

oss:PutObject

oss:GetObjectVersion

Necessária também ao especificar a versão do objeto de origem via versionId.

oss:GetObjectTagging

Obrigatórias ao copiar tags de objeto via x-oss-tagging.

oss:PutObjectTagging

oss:GetObjectVersionTagging

Também necessária caso as tags de uma versão específica do objeto de origem sejam definidas via versionId.

kms:GenerateDataKey

Ambas as permissões são obrigatórias se os metadados do objeto de destino contiverem X-Oss-Server-Side-Encryption: KMS durante a cópia.

kms:Decrypt

Código de exemplo

O código a seguir demonstra 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