Todos os produtos
Search
Central de documentação

Object Storage Service:Copiar um objeto (Harmony SDK)

Última atualização: Jul 03, 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 mesmo bucket de origem ou um bucket diferente.

Observações

  • Para obter mais informações sobre regiões e endpoints suportados, consulte Regiões e endpoints do OSS.

  • Para copiar um objeto, você deve ter permissões 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 localizados na mesma região. Por exemplo, objetos em um bucket localizado na região China (Hangzhou) não podem ser copiados para um bucket localizado na região China (Qingdao).

  • Verifique se não há políticas de retenção configuradas para o bucket de origem e o bucket de destino. Caso contrário, a mensagem de erro The object you specified is immutable. será retornada.

Permissões

Por padrão, uma conta Alibaba Cloud possui permissões totais. 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 as permissões de operação por meio de políticas do 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 caso você especifique a versão do objeto de origem por meio de versionId.

oss:GetObjectTagging

Obrigatórias quando tags de objeto são copiadas via x-oss-tagging.

oss:PutObjectTagging

oss:GetObjectVersionTagging

Também exigida se as tags de uma versão específica do objeto de origem forem definidas usando versionId.

kms:GenerateDataKey

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

kms:Decrypt

Exemplo de código

Abaixo está 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();