Todos os produtos
Search
Central de documentação

Object Storage Service:Definir tags de objeto (SDK para Node.js)

Última atualização: Jul 03, 2026

O Object Storage Service (OSS) permite configurar tags de objeto para classificar objetos. Configure regras de ciclo de vida e controle o acesso aos objetos com base nessas tags.

Observações de uso

  • Antes de configurar a marcação de objetos, familiarize-se com o recurso. Para mais informações, consulte Marcação de objetos.

  • 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 a criação de 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.

  • Somente o OSS SDK for Java 3.5.0 ou posterior oferece suporte à marcação de objetos.

  • Para adicionar uma tag a um objeto, é necessária a permissão oss:PutObjectTagging. Para mais informações, consulte Conceder uma política personalizada.

Adicionar tags de objeto durante o upload do objeto

  • Adicionar tags de objeto durante um upload simples

    O código a seguir mostra como adicionar tags de objeto durante um upload simples usando o método PutObject.

    const OSS = require('ali-oss')
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
      bucket: 'yourbucketname'
    });
    
    // Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
    const objectName = 'exampledir/exampleobject.txt'
    // Specify the full path of the local file. For example, D:\\localpath\\examplefile.txt.
    // If you specify only the local file name (for example, examplefile.txt) without a full path, the file is uploaded from the local path that corresponds to the project of the sample program.
    const localFilepath = 'D:\\localpath\\examplefile.txt'
    
    // Set request headers.
    const headers = {
      // Specify the key (for example, owner) and value (for example, John) of the object tag.
      'x-oss-tagging': 'owner=John&type=document', 
    }
    
    client.put(objectName, localFilepath, {
      headers
    })
  • Adicionar tags de objeto durante um upload multipart

    O código a seguir mostra como adicionar tags de objeto durante um upload multipart usando o método multipartUpload.

    const OSS = require('ali-oss')
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
      bucket: 'yourbucketname'
    });
    
    // Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
    const objectName = 'exampledir/exampleobject.txt'
    // Specify the full path of the local file. For example, D:\\localpath\\examplefile.txt.
    // If you specify only the local file name (for example, examplefile.txt) without a full path, the file is uploaded from the local path that corresponds to the project of the sample program.
    const localFilepath = 'D:\\localpath\\examplefile.txt'
    
    // Set request headers.
    const headers = {
      // Specify the key (for example, owner) and value (for example, John) of the object tag.
      'x-oss-tagging': 'owner=John&type=document', 
    }
    
    async function setTag() {
      await client.multipartUpload(objectName, localFilepath, {
        // Set the part size in bytes. The minimum part size is 100 KB. The size of the last part is not limited.
        partSize: 100 * 1024,
        headers
      });
      const tag = await client.getObjectTagging(objectName);
      console.log(tag);
    }
    
    setTag()
  • Adicionar tags de objeto durante um upload por acréscimo

    O código a seguir mostra como adicionar tags de objeto durante um upload por acréscimo usando o método AppendObject.

    const OSS = require('ali-oss')
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
      bucket: 'yourbucketname'
    });
    
    // Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
    const objectName = 'exampledir/exampleobject.txt'
    // Specify the full path of the local file. For example, D:\\localpath\\examplefile.txt.
    // If you specify only the local file name (for example, examplefile.txt) without a full path, the file is uploaded from the local path that corresponds to the project of the sample program.
    const localFilepath = 'D:\\localpath\\examplefile.txt'
    
    // Set request headers.
    const headers = {
      // Specify the key (for example, owner) and value (for example, John) of the object tag.
      'x-oss-tagging': 'owner=John&type=document',
    }
    
    // Append data to an object. If you specify headers in the append operation, tags are set for the object.
    // Only the tags set in the first append operation take effect. Tags set in subsequent append operations are ignored.
    async function setTag() {
      await client.append(objectName, localFilepath, {
        // Set the part size in bytes. The minimum part size is 100 KB. The size of the last part is not limited.
        partSize: 100 * 1024,
        headers
      });
      const tag = await client.getObjectTagging(objectName);
      console.log(tag);
    }
    
    setTag()
  • Adicionar tags de objeto durante um upload retomável

    O código a seguir mostra como adicionar tags de objeto durante um upload retomável usando o método multipartUpload.

    const OSS = require('ali-oss')
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
      bucket: 'yourbucketname'
    });
    
    // Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
    const objectName = 'exampledir/exampleobject.txt'
    // Specify the full path of the local file. For example, D:\\localpath\\examplefile.txt.
    // If you specify only the local file name (for example, examplefile.txt) without a full path, the file is uploaded from the local path that corresponds to the project of the sample program.
    const localFilepath = 'D:\\localpath\\examplefile.txt'
    // Set the breakpoint information.
    let checkpoint;
    
    // Set request headers.
    const headers = {
      // Specify the key (for example, owner) and value (for example, John) of the object tag.
      'x-oss-tagging': 'owner=John&type=document',
    }
    
    async function setTag() {
      await client.multipartUpload(objectName, localFilepath, {
        checkponit,
        async progress(percentage, cpt) {
          checkpoint = cpt;
        },
        headers
      });
      const tag = await client.getObjectTagging(objectName);
      console.log(tag);
    }
    
    setTag()

Adicionar ou alterar tags de um objeto existente

Se um objeto existente não tiver tags ou se as tags atuais não atenderem aos seus requisitos, adicione novas tags ou modifique as existentes.

O código a seguir mostra como adicionar ou alterar tags de um objeto existente.

const OSS = require('ali-oss')

const client = new OSS({
  // Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
  bucket: 'yourbucketname'
});

// Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
const objectName = 'exampledir/exampleobject.txt'
// Specify the key (for example, owner) and value (for example, John) of the object tag.
const tag = { owner: 'John', type: 'document' };

async function putObjectTagging(objectName, tag) {
  try {
    const result = await client.putObjectTagging(objectName, tag);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

putObjectTagging(objectName, tag)

Adicionar ou alterar tags de uma versão específica do objeto

Com o versionamento ativado para um bucket, especifique o ID da versão para adicionar ou modificar tags de uma versão específica de um objeto nesse bucket.

O código a seguir mostra como adicionar ou alterar tags de uma versão específica de um objeto.

Nota

Para mais informações sobre como obter um ID de versão, consulte Listar objetos (SDK para Node.js).

const OSS = require('ali-oss')

const client = new OSS({
  // Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
  bucket: 'yourbucketname'
});

// Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
const objectName = 'exampledir/exampleobject.txt'
// Specify the key (for example, owner) and value (for example, John) of the object tag.
const tag = { owner: 'John', type: 'document' };
// Specify the version ID of the object.
const versionId='CAEQIRiBgMDqvPqA3BciIDJhMjE4MWZkN2ViYTRmYzJhZjkxMzk2YWM2NjJk****'

async function putObjectTagging(objectName, tag) {
  try {
    const options = {
      versionId
    };
    const result = await client.putObjectTagging(objectName, tag, options);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

putObjectTagging(objectName, tag)

Definir tags de objeto ao copiar um objeto

Use um dos métodos a seguir para configurar a marcação de objetos ao copiar um objeto:

  • Copiar: a tag do objeto de origem é copiada para o objeto de destino.

  • Substituir: o objeto de destino recebe a tag especificada na solicitação em vez da tag do objeto de origem.

Os exemplos a seguir descrevem como adicionar tags a um objeto menor que 1 GB no modo de cópia simples e maior que 1 GB no modo de cópia multipart:

  • Adicionar tags de objeto durante uma cópia simples

    O código a seguir mostra como definir tags de objeto ao realizar uma cópia simples de um objeto menor que 1 GB.

    const OSS = require('ali-oss')
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
      bucket: 'yourbucketname'
    });
    
    // Specify the full path of the source object. The full path cannot contain the bucket name. For example, srcexampledir/exampleobject.txt.
    const sourceObjectName = 'srcexampledir/exampleobject.txt';
    // Specify the full path of the destination object. The full path cannot contain the bucket name. For example, destexampledir/exampleobject.txt.
    const targetObjectName = 'destexampledir/exampleobject.txt';
    
    // Set request headers.
    const headers = {
      // Specify the key (for example, owner) and value (for example, John) of the object tag.
      'x-oss-tagging': 'owner=John&type=document',
      // Specify how to set the tags for the destination object. Valid values: Copy and Replace. The default value is Copy. Copy indicates that the tags of the source object are copied to the destination object. Replace indicates that the tags of the source object are ignored and the tags specified in the request are used.
      'x-oss-tagging-directive': 'Replace' 
    }
    
    async function setTag() {
      const result = await client.copy(targetObjectName, sourceObjectName, {
        headers
      });
      const tag = await client.getObjectTagging(targetObjectName)
      console.log(tag)
    }
    
    setTag()
  • Adicionar tags de objeto durante uma cópia multipart

    O código a seguir mostra como definir tags de objeto ao realizar uma cópia multipart de um objeto maior que 1 GB.

    const OSS = require('ali-oss')
    
    const client = new OSS({
      // Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
      bucket: 'yourbucketname'
    });
    
    // Specify the full path of the source object. The full path cannot contain the bucket name. For example, srcexampledir/exampleobject.txt.
    const sourceObjectName = 'srcexampledir/exampleobject.txt'
    // Specify the full path of the destination object. The full path cannot contain the bucket name. For example, destexampledir/exampleobject.txt.
    const targetObjectName = 'destexampledir/exampleobject.txt'
    
    // Set request headers.
    const headers = {
      // Specify the key (for example, owner) and value (for example, John) of the object tag.
      'x-oss-tagging': 'owner=John&type=document',
    }
    
    async function setTag() {
      await client.multipartUploadCopy(targetObjectName, {
        sourceKey: sourceObjectName,
        sourceBucketName: 'examplebucket'
      }, {
        // Set the part size in bytes. The minimum part size is 100 KB. The size of the last part is not limited.
        partSize: 256 * 1024,
        headers
      });
      const tag = await client.getObjectTagging(targetObjectName)
      console.log(tag)
    }
    
    setTag()

Definir tags para um link simbólico

O código a seguir mostra como definir tags para um link simbólico.

const OSS = require('ali-oss')

const client = new OSS({
  // Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
  bucket: 'yourbucketname'
});

// Specify the full path of the symbolic link. For example, shortcut/myobject.txt.
const symLink = "shortcut/myobject.txt";
// Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
const targetObjectName = 'exampledir/exampleobject.txt'
                
// Set request headers.
const headers = {
  // Specify the key (for example, owner) and value (for example, John) of the object tag.
  'x-oss-tagging': 'owner=John&type=document',
}

async function setTag() {
  await client.putSymlink(symLink, targetObjectName, {
    storageClass: 'IA',
    meta: {
      uid: '1',
      slus: 'test.html'
    },
    headers
  });
  const tag = await client.getObjectTagging(targetObjectName)
  console.log(tag)
}

setTag()

Referências

  • Para ver o código de exemplo completo sobre como definir tags de objeto, consulte o GitHub.

  • Para mais informações sobre a operação de API para definir tags de objeto, consulte PutObjectTagging.