Todos os produtos
Search
Central de documentação

Object Storage Service:Copy an object (Harmony SDK)

Última atualização: Sep 22, 2026

Este tópico descreve como usar o método CopyObject do OSS SDK for Harmony para copiar um objeto com tamanho inferior a 5 GiB de um bucket de origem para um bucket de destino na mesma região. O bucket de destino pode ser o próprio bucket de origem ou um bucket diferente.

Observações

  • Para mais informações sobre regiões e endpoints compatíveis, consulte OSS regions and endpoints.

  • Para copiar um objeto, você deve ter permissão de leitura no objeto de origem e permissões de leitura e gravação no bucket de destino.

  • Os buckets de origem e de destino devem estar na mesma região. Por exemplo, não é possível copiar objetos de um bucket na região China (Hangzhou) para um bucket na região China (Qingdao).

  • Certifique-se de que os buckets de origem e de destino não possuam políticas de retenção configuradas. Caso contrário, o sistema retornará a mensagem de erro The object you specified is immutable..

Permissões

Por padrão, uma conta Alibaba Cloud tem acesso total. Usuários RAM e funções RAM associados a uma conta Alibaba Cloud não têm permissões por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de RAM policies 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

Caso especifique a versão do objeto de origem por meio do versionId, esta permissão também é necessária.

oss:GetObjectTagging

Se você copiar as tags do objeto usando x-oss-tagging, estas permissões são necessárias.

oss:PutObjectTagging

oss:GetObjectVersionTagging

Caso especifique as tags de uma versão específica do objeto de origem por meio do versionId, esta permissão também é necessária.

kms:GenerateDataKey

Ao copiar um objeto, se os metadados do objeto de destino contiverem X-Oss-Server-Side-Encryption: KMS, estas duas permissões serão necessárias.

kms:Decrypt

Código de exemplo

Confira a seguir um exemplo de código para copiar objetos dentro do mesmo bucket.

import Client, { RequestError } from '@aliyun/oss';

// Create an OSSClient instance.
const client = new Client({
  // Specify the AccessKey ID obtained from Security Token Service (STS).
  accessKeyId: 'yourAccessKeyId',
  // Specify the AccessKey secret obtained from STS.
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the security token obtained from STS.
  securityToken: 'yourSecurityToken',
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

/**
 * Copy an object to the same bucket.
 * Use the copyObject method to copy the source object to the destination object.
 */
const copyObject = async () => {
  try {
    // Use the copyObject method to copy an object to the same bucket.
    const res = await client.copyObject({
      bucket: 'targetBucket', // Name of the destination bucket.
      key: 'targetKey',       // Name of the destination object.
      copySourceKey: 'sourceKey', // Name of the source object. 
    });

    // Output the result.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Capture exceptions.
    if (err instanceof RequestError) {
      console.log('code: ', err.code); // Error code.
      console.log('message: ', err.message); // Error message.
      console.log('requestId: ', err.requestId); // Request ID.
      console.log('status: ', err.status); // HTTP status code.
      console.log('ec: ', err.ec); // EC
    } else {
      console.log('unknown error: ', err);
    }
  }
};

// Call the copyObject function to copy the object to the same bucket.
copyObject();

Cenário comum

Copiar objetos de um bucket de origem para um bucket de destino na mesma região

import Client, { RequestError } from '@aliyun/oss';

// Create an OSSClient instance.
const client = new Client({
  // Specify the AccessKey ID obtained from STS.
  accessKeyId: 'yourAccessKeyId',
  // Specify the AccessKey secret obtained from STS.
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the security token obtained from STS.
  securityToken: 'yourSecurityToken',
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

/**
 * Copy an object from another bucket.
 * Use the copyObject method to copy an object from the source bucket to the destination bucket.
 */
const copyObjectFromOtherBucket = async () => {
  try {
    // Call the copyObject method to copy an object from another bucket.
    const res = await client.copyObject({
      bucket: 'targetBucket', // Name of the destination bucket. 
      key: 'targetKey',       // Name of the destination object.
      copySourceBucket: 'sourceBucket', // Name of the source bucket. 
      copySourceKey: 'sourceKey',       // Name of the source object. 
    });

    // Output the result.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Capture exceptions.
    if (err instanceof RequestError) {
      console.log('code: ', err.code); // Error code.
      console.log('message: ', err.message); // Error message.
      console.log('requestId: ', err.requestId); // Request ID.
      console.log('status: ', err.status); // HTTP status code.
      console.log('ec: ', err.ec); // EC
    } else {
      console.log('unknown error: ', err);
    }
  }
};

// Call the copyObjectFromOtherBucket function to copy the object from another bucket.
copyObjectFromOtherBucket();