Todos os produtos
Search
Central de documentação

Object Storage Service:copy an object (browser.js sdk)

Última atualização: Jul 03, 2026

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

Observações

  • Ao usar ferramentas de empacotamento como Webpack e Browserify, instale o OSS SDK for Browser.js executando o comando npm install ali-oss.

  • O OSS SDK for Browser.js é usado principalmente em navegadores. Para evitar a exposição do seu par de AccessKey, use credenciais de acesso temporárias obtidas pelo Security Token Service (STS) para acessar o OSS.

    As credenciais de acesso temporárias consistem em um par de AccessKey e um token de segurança. O par de AccessKey inclui um AccessKey ID e um AccessKey secret. Para mais informações sobre como obter credenciais de acesso temporárias, consulte Usar STS para autorização de acesso temporário.

  • Os buckets de origem e destino da operação de cópia devem ter regras de compartilhamento de recursos de origem cruzada (CORS) configuradas. Para mais informações, consulte Preparações.

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 têm permissões atribuídas inicialmente. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões operacionais necessárias 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 source via versionId.

oss:GetObjectTagging

Obrigatórias ao copiar tags do objeto usando x-oss-tagging.

oss:PutObjectTagging

oss:GetObjectVersionTagging

Necessária também ao especificar as tags de uma versão específica do objeto de source via versionId.

kms:GenerateDataKey

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

kms:Decrypt

Copiar um objeto dentro de um bucket

O código a seguir mostra como copiar o objeto srcobject.txt para destobject.txt dentro do bucket examplebucket.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Document</title>
</head>

<body>
  <button id='upload'>Upload</button>
  <button id='copy'>Copy</button>
    <!--Import the SDK file.-->
  <script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
  <script type="text/javascript">
    const client = new OSS({
       // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
       region: 'yourRegion',
       authorizationV4: true,
       // The temporary AccessKey ID and AccessKey secret obtained from STS.
       accessKeyId: 'yourAccessKeyId',
       accessKeySecret: 'yourAccessKeySecret',
       // The security token obtained from STS.
       stsToken: 'yourSecurityToken',
       // Specify the bucket name. Example: examplebucket.
       bucket: "examplebucket",
     });

    const upload = document.getElementById('upload')
    const copy = document.getElementById('copy')

    // Specify the content of the object to upload.
    const file = new Blob(['examplecontent'])
    // Specify the full path of the object to upload. Example: srcobject.txt.
    const fileName = 'srcobject.txt'

    // Upload the object.
    upload.addEventListener('click', () => {
      const result = client.put(fileName, file).then(r => console.log(r))
    })

    // Copy the object.
    copy.addEventListener('click', () => {
      // Specify the name of the destination object.
      client.copy('destobject.txt', fileName
        // Set the HTTP headers and custom metadata for the destination object.
        //{
            // Specify the headers parameter to set the HTTP headers for the destination object. If you do not specify this parameter, the destination object has the same HTTP headers as the source object.
            // headers:{
            //'Cache-Control': 'no-cache',        
            // The copy operation is performed only if the ETag of the source object matches the specified ETag.
            //'if-match': '5B3C1A2E053D763E1B002CC607C5****',
            // The copy operation is performed only if the ETag of the source object does not match the specified ETag.
            //'if-none-match': '5B3C1A2E053D763E1B002CC607C5****', 
            // The copy operation is performed only if the source object has been modified since the specified time.
            //'if-modified-since': '2021-12-09T07:01:56.000Z', 
            // The copy operation is performed only if the source object has not been modified since the specified time.
            //'if-unmodified-since': '2021-12-09T07:01:56.000Z', 
            // Specify the access control list (ACL) for the destination object. In this example, the ACL is set to private. This means only the object owner and authorized users have read and write permissions. Other users cannot access the object.
            //'x-oss-object-acl': 'private', 
            // Specify the tags for the object. You can specify multiple tags.
            //'x-oss-tagging': 'Tag1=1&Tag2=2',
            // Specify whether to overwrite a destination object that has the same name. In this example, the value is set to true to prevent overwriting.
            //'x-oss-forbid-overwrite': 'true', 
    //},
        // Specify the meta parameter to customize the metadata of the destination object. If you do not specify this parameter, the destination object has the same metadata as the source object.
        // meta:{
            // location: 'hangzhou',
            // year: 2015,
            // people: 'mary'
        //}
        // }
      ).then(r => {
        console.log(r.res.status)
      })
    })

  </script>
</body>

</html>

Copiar um objeto entre buckets

O código a seguir mostra como copiar o objeto srcobject.txt do bucket de source srcbucket para o objeto destobject.txt no bucket de destino destbucket.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <button id="copy">Copy</button>
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
        region: "yourRegion",
        authorizationV4: true,
        // The temporary AccessKey ID and AccessKey secret obtained from STS.
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // The security token obtained from STS.
        stsToken: "yourSecurityToken",
        // Specify the destination bucket name.
        bucket: "destbucket",
      });
      const copy = document.getElementById("copy");

      copy.addEventListener("click", () => {
        client
          .copy(
            // Specify the name of the destination object.
            "srcobject.txt",
            // Specify the name of the source object.
            "destobject.txt",
            // Specify the source bucket name.
            "srcbucket"
          )
          .then((r) => console.log(r));
      });
    </script>
  </body>
</html>

Referências

  • Para obter o código de exemplo completo sobre cópia de objetos, consulte os exemplos no GitHub.

  • Para mais informações sobre a operação de API de cópia de objetos, consulte CopyObject.