Todos os produtos
Search
Central de documentação

Object Storage Service:Copiar objetos (SDK para Node.js)

Última atualização: Jul 03, 2026

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

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints compatíveis, consulte Regiões e endpoints.

  • As credenciais de acesso neste tópico são obtidas de variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configuração do cliente.

  • Você deve ter permissões de leitura no objeto de origem e permissões de leitura/gravação no bucket de destino.

  • Os buckets de origem e de destino não podem ter políticas de retenção configuradas. Caso contrário, a cópia falhará e o sistema retornará o erro The object you specified is immutable..

  • Não há suporte para cópia entre regiões. Por exemplo, você não pode copiar um objeto de um bucket na China (Hangzhou) para um bucket na China (Qingdao).

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados 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 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

Se você especificar a versão do objeto de origem por meio de versionId, esta permissão também será necessária.

oss:GetObjectTagging

Ao copiar tags de objetos via x-oss-tagging, estas permissões são obrigatórias.

oss:PutObjectTagging

oss:GetObjectVersionTagging

Caso especifique as tags de uma versão específica do objeto de origem usando versionId, esta permissão também é exigida.

kms:GenerateDataKey

Durante a cópia de um objeto, se os metadados do objeto de destino contiverem X-Oss-Server-Side-Encryption: KMS, ambas as permissões serão necessárias.

kms:Decrypt

Copiar um objeto pequeno

Use o método copy para copiar um objeto com tamanho de até 1 GB dentro do mesmo bucket ou para outro bucket na mesma região.

  • Copiar um objeto dentro do mesmo bucket

    O código de exemplo a seguir mostra como copiar um objeto dentro do mesmo bucket.

    const OSS = require('ali-oss');
    const client = new OSS({
      // 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: 'yourRegion',
      // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the name of the bucket. Example: examplebucket.
      bucket: 'examplebucket',
      // Specify whether to enable HTTPS. If you set secure to true, HTTPS is enabled.
      // secure: true
    })
    
    // Copy an object within a bucket.
    async function copySmallObjecInSameBucket() {
      try {
        // Specify the full paths of the destination object and source object. Do not include the bucket name in the full paths.
        // Specify HTTP headers and custom metadata for the destination object.
        const result = await client.copy('destexampleobject.txt', 'srcexampleobject.txt', {
          // Configure the headers parameter to specify HTTP headers for the destination object. If you do not configure the headers parameter, the HTTP headers of the destination object are the same as the HTTP headers of the source object. The HTTP headers of the source object are copied.
          headers: {
            'Cache-Control': 'no-cache',
            // If the ETag value of the source object is the same as the ETag value specified in the request, OSS copies the object and returns 200 OK.
            'if-match': '5B3C1A2E053D763E1B002CC607C5****',
            // If the ETag value that you specify in the request is different from the ETag value of the source object, OSS copies the object and returns 200 OK.
            'if-none-match': '5B3C1A2E053D763E1B002CC607C5****',
            // If the time that is specified in the request is earlier than the time when the object is modified, OSS copies the object and returns 200 OK.
            'if-modified-since': '2021-12-09T07:01:56.000Z',
            // If the source object has not been modified since the specified time, the object is copied and 200 OK is returned.
            'if-unmodified-since': '2021-12-09T07:01:56.000Z',
            // Specify the access control list (ACL) of the destination object. In this example, the ACL is set to private, which indicates that only the object owner and authorized users have read and write permissions on the object. Other users do not have permissions to access the object.
            'x-oss-object-acl': 'private',
            // Specify tags for the object. You can specify multiple tags for the object at the same time.
            'x-oss-tagging': 'Tag1=1&Tag2=2',
            // Specify whether the CopyObject operation overwrites an existing object that has the same name. In this example, this parameter is set to true, which specifies that the CopyObject operation does not overwrite an existing object that has the same name.
            'x-oss-forbid-overwrite': 'true',
          },
          // Configure the meta parameter to specify the metadata of the destination object. If you do not configure the meta parameter, the metadata of the destination object is the same as the metadata of the source object. The metadata of the source object is copied.
          meta: {
            location: 'hangzhou',
            year: 2015,
            people: 'mary',
          },
        });
        console.log(result);
      } catch (e) {
        console.log(e);
      }
    }
    
    copySmallObjecInSameBucket()
  • Copiar um objeto entre buckets na mesma região

    O código de exemplo a seguir ilustra como copiar um objeto entre buckets na mesma região.

    const OSS = require('ali-oss');
    const client = new OSS({
    
      // 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: 'yourRegion',
      // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      authorizationV4: true,
      // Specify the name of the destination bucket.
      bucket: 'destexamplebucket',
    });
    
    async function copySmallObjectBetweenBuckets() {
      try {
        // Specify the name of the destination object destobject.txt, the name of the source object srcobject.txt, and the name of the bucket to which the source object belongs.
        const result = await client.copy('destobject.txt', 'srcobject.txt', 'srcbucket', {
          // Configure the headers parameter to specify HTTP headers for the destination object. If you do not configure the headers parameter, the HTTP headers of the destination object are the same as the HTTP headers of the source object. The HTTP headers of the source object are copied.
          headers: {
            'Cache-Control': 'no-cache',
          },
          // Configure the meta parameter to specify the metadata of the destination object. If you do not configure the meta parameter, the metadata of the destination object is the same as the metadata of the source object. The metadata of the source object is copied.
          meta: {
            location: 'hangzhou',
            year: 2015,
            people: 'mary',
          },
        });
        console.log(result);
      } catch (e) {
        console.log(e);
      }
    }
    
    copySmallObjectBetweenBuckets()

Copiar um objeto grande

Para objetos maiores que 1 GB, use o método multipartUploadCopy para executar uma cópia multipart.

O código de exemplo a seguir demonstra como copiar um objeto entre buckets na mesma região.

const OSS = require("ali-oss");

const client = new OSS({
  // 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: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of the destination bucket.
  bucket: "destexamplebucket",
});

async function copyLargeObjectBetweenDifferentBuckets() {
  try {
    const copyheaders = {
      // If the ETag value of the source object is the same as the ETag value that is specified in the request, OSS copies the object. Otherwise, OSS returns the HTTP status code 412 (PreconditionFailed).
      "x-oss-copy-source-if-match": "5B3C1A2E053D763E1B002CC607C5****",
      // If the ETag value of the source object is different from the ETag value that is specified in the request, OSS copies the object and returns 200 OK. Otherwise, OSS returns the HTTP status code 304 (NotModified).  
      "x-oss-copy-source-if-none-match": "5B3C1A2E053D763E1B002CC607C5****",
      // If the time that is specified in the request is later than or the same as the time when the object is modified, OSS copies the object and returns 200 OK. Otherwise, OSS returns the HTTP status code 412 (PreconditionFailed).  
      "x-oss-copy-source-if-unmodified-since": "2022-12-09T07:01:56.000Z",
      // If the time that is specified in the request is earlier than the time when the object is modified, OSS copies the object and returns 200 OK. Otherwise, OSS returns the HTTP status code 304 (NotModified).
      "x-oss-copy-source-if-modified-since": "2022-12-09T07:01:56.000Z",
    };

    const headers = {
      // Specify the caching behavior of the web page when the object is downloaded.
      "Cache-Control": "no-cache",
      // Specify the name of the object when the object is downloaded.
      "Content-Disposition": "somename",
      // Specify the expiration time in milliseconds.
      Expires: "1000",
    };

    let savedCpt;
    // Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject1.txt.
    const r1 = await client.multipartUploadCopy("destexampleobject1.txt", {
      // Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
      sourceKey: "srcexampleobject.txt",
      // Specify the name of the source bucket. Example: sourcebucket.  
      sourceBucketName: "sourcebucket",
      copyheaders: copyheaders,
    });
    console.log(r1);

    // Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject2.txt.
    const r2 = await client.multipartUploadCopy("destexampleobject2.txt", {
      // Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
      sourceKey: "srcexampleobject.txt",
      // Specify the name of the source bucket. Example: sourcebucket.
      sourceBucketName: "sourcebucket",
    }, {
      // Set the number of parts that can be uploaded in parallel.
      parallel: 4,
      // Set the part size.
      partSize: 1024 * 1024,
      progress: function (p, cpt, res) {
        console.log(p);
        savedCpt = cpt;
        console.log(cpt);
        console.log(res.headers["x-oss-request-id"]);
      },
      headers: headers,
      copyheaders: copyheaders,
    });
    console.log(r2);

    // Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampleobject3.txt.
    const r3 = await client.multipartUploadCopy("destexampleobject3.txt", {
      // Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
      sourceKey: "srcexampleobject.txt",
      // Specify the name of the source bucket. Example: sourcebucket.
      sourceBucketName: "sourcebucket",
    }, {
      checkpoint: savedCpt,
      progress: function (p, cpt, res) {
        console.log(p);
        console.log(cpt);
        console.log(res.headers["x-oss-request-id"]);
      },
    });
    console.log(r3);
  } catch (e) {
    console.log(e);
  }
}

copyLargeObjectBetweenDifferentBuckets()

Referências

  • Copiar um objeto pequeno

    • Para obter o código de exemplo completo sobre como copiar um objeto pequeno, consulte o exemplo no GitHub.

    • Para mais detalhes sobre a operação de API destinada à cópia de objetos pequenos, consulte CopyObject.

  • Copiar um objeto grande

    • O código de exemplo completo para copiar objetos grandes está disponível no exemplo do GitHub.

    • Saiba mais sobre a operação de API para cópia de objetos grandes em UploadPartCopy.