Todos os produtos
Search
Central de documentação

Object Storage Service:Copy objects (Node.js SDK)

Última atualização: Sep 24, 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 do Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints suportados, consulte Regions and endpoints.

  • Neste tópico, você obtém as credenciais de acesso a partir de variáveis de ambiente. Para mais informações, consulte 配置访问凭证.

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

  • 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 não devem ter políticas de retenção configuradas. Caso contrário, a cópia falhará e a operação retornará o erro The object you specified is immutable..

  • O OSS não suporta cópias entre regiões. Por exemplo, você não pode copiar um objeto de um bucket em China (Hangzhou) para um bucket em China (Qingdao).

Permissões

Por padrão, uma conta Alibaba Cloud possui permissões totais. Usuários RAM ou funções RAM sob uma conta Alibaba Cloud não possuem 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 será necessária.

oss:GetObjectTagging

Se você copiar tags de objeto por meio do 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 será 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

Copiar um objeto pequeno

Você pode usar o método copy para copiar um objeto com tamanho de até 1 GB dentro do mesmo bucket ou para um bucket diferente 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 mostra como copiar um objeto entre buckets na mesma região.

    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 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, você pode usar o método multipartUploadCopy para executar uma cópia multipart.

O código de exemplo a seguir mostra 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 o código de exemplo completo para copiar um objeto pequeno, consulte o exemplo no GitHub.

    • Para mais informações sobre a operação de API para copiar um objeto pequeno, consulte CopyObject.

  • Copiar um objeto grande

    • Para o código de exemplo completo para copiar um objeto grande, consulte o exemplo no GitHub.

    • Para mais informações sobre a operação de API para copiar um objeto grande, consulte UploadPartCopy.