Todos los productos
Search
Centro de documentos

Object Storage Service:Establecer etiquetas de objetos (SDK de Node.js)

Última actualización: Sep 25, 2026

Object Storage Service (OSS) le permite configurar etiquetas en los objetos para clasificarlos. Con base en estas etiquetas, puede definir reglas de ciclo de vida y controlar el acceso a los objetos.

Notas de uso

  • Antes de configurar el etiquetado de objetos, asegúrese de conocer bien esta función. Para obtener más información, consulte Object tagging.

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si accede a OSS desde otros servicios de Alibaba Cloud dentro de la misma región, use un endpoint interno. Para conocer las regiones y los endpoints compatibles, consulte Regions and endpoints.

  • Las credenciales de acceso de este tema se obtienen de variables de entorno. Para obtener más información, consulte 配置访问凭证.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para otras configuraciones, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Client configuration.

  • Solo OSS SDK for Java 3.5.0 y versiones posteriores admiten el etiquetado de objetos.

  • Para agregar una etiqueta a un objeto, necesita el permiso oss:PutObjectTagging. Para obtener más información, consulte Grant a custom policy.

Agregar etiquetas durante la carga de un objeto

  • Agregar etiquetas durante una carga simple

    A continuación se muestra cómo agregar etiquetas a un objeto durante una carga simple mediante el 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
    })
  • Agregar etiquetas durante una carga por partes

    A continuación se muestra cómo agregar etiquetas a un objeto durante una carga por partes mediante el 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()
  • Agregar etiquetas durante una carga por anexión

    A continuación se muestra cómo agregar etiquetas a un objeto durante una carga por anexión mediante el 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()
  • Agregar etiquetas durante una carga reanudable

    A continuación se muestra cómo agregar etiquetas a un objeto durante una carga reanudable mediante el 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()

Agregar o modificar etiquetas de un objeto existente

Si un objeto existente no tiene etiquetas o las actuales no cumplen sus requisitos, puede agregar nuevas o modificar las que ya tiene.

A continuación se muestra cómo agregar o cambiar las etiquetas de un 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)

Agregar o modificar etiquetas de una versión específica de un objeto

Si el control de versiones está habilitado en un bucket, puede agregar o modificar las etiquetas de una versión específica de un objeto. Para ello, especifique el identificador de versión del objeto.

A continuación se muestra cómo agregar o cambiar las etiquetas de una versión específica de un objeto.

Nota

Para obtener más información sobre cómo conseguir un identificador de versión, consulte List objects (Node.js SDK).

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)

Establecer etiquetas al copiar un objeto

Al copiar un objeto, puede configurar las etiquetas con uno de los siguientes métodos:

  • Copy: la etiqueta del objeto de origen se copia al objeto de destino.

  • Replace: el objeto de destino usa la etiqueta especificada en la solicitud en lugar de la del objeto de origen.

Los siguientes ejemplos muestran cómo agregar etiquetas a un objeto menor a 1 GB en modo de copia simple y a uno mayor a 1 GB en modo de copia por partes:

  • Agregar etiquetas durante una copia simple

    A continuación se muestra cómo establecer etiquetas al ejecutar una copia simple de un objeto menor a 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()
  • Agregar etiquetas durante una copia por partes

    A continuación se muestra cómo establecer etiquetas al ejecutar una copia por partes de un objeto mayor a 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()

Establecer etiquetas para un enlace simbólico

A continuación se muestra cómo establecer etiquetas para un enlace 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()

Referencias

  • Para consultar el código de ejemplo completo sobre cómo establecer etiquetas de objetos, visite GitHub.

  • Para obtener más información sobre la operación de API que establece etiquetas de objetos, consulte PutObjectTagging.