Tous les produits
Search
Centre de documentation

Object Storage Service:Définir des tags d'objet (SDK Node.js)

Dernière mise à jour :Sep 25, 2026

Object Storage Service (OSS) vous permet de configurer des tags d'objet pour classer vos objets. Vous pouvez définir des règles de cycle de vie et contrôler l'accès aux objets en fonction de ces tags.

Notes d'utilisation

  • Avant de configurer le tagging d'objet, assurez-vous de bien comprendre cette fonctionnalité. Pour plus d'informations, consultez la rubrique Tagging d'objet.

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un point de terminaison interne. Pour obtenir la liste des régions et des points de terminaison pris en charge, consultez la rubrique Régions et points de terminaison.

  • Dans cette rubrique, les identifiants d'accès sont récupérés à partir des variables d'environnement. Pour plus d'informations, consultez la rubrique Configuration des informations d'identification d'accès.

  • Cette rubrique explique comment créer une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez la rubrique Configuration du client.

  • Seul le SDK OSS pour Java version 3.5.0 et ultérieure prend en charge le tagging d'objet.

  • Pour ajouter un tag à un objet, vous devez disposer de l'autorisation oss:PutObjectTagging. Pour plus d'informations, consultez la rubrique Accorder une stratégie personnalisée.

Ajouter des tags d'objet lors du chargement d'un objet

  • Ajouter des tags d'objet lors d'un chargement simple

    Le code suivant montre comment ajouter des tags d'objet lors d'un chargement simple à l'aide de la méthode 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
    })
  • Ajouter des tags d'objet lors d'un chargement multipartie

    Le code suivant montre comment ajouter des tags d'objet lors d'un chargement multipartie à l'aide de la méthode 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()
  • Ajouter des tags d'objet lors d'un chargement par ajout

    Le code suivant montre comment ajouter des tags d'objet lors d'un chargement par ajout à l'aide de la méthode 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()
  • Ajouter des tags d'objet lors d'une reprise de chargement

    Le code suivant montre comment ajouter des tags d'objet lors d'une reprise de chargement à l'aide de la méthode 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()

Ajouter ou modifier des tags d'objet pour un objet existant

Si un objet existant ne possède pas de tags ou si ses tags ne répondent pas à vos besoins, vous pouvez lui ajouter des tags ou modifier ceux qui sont déjà présents.

Le code suivant montre comment ajouter ou modifier des tags d'objet pour un objet existant.

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)

Ajouter ou modifier des tags d'objet pour une version spécifique d'un objet

Si le versioning est activé pour un bucket, vous pouvez ajouter des tags à une version spécifique d'un objet ou modifier ses tags en indiquant l'ID de version de l'objet.

Le code suivant montre comment ajouter ou modifier des tags d'objet pour une version spécifique d'un objet.

Remarque

Pour savoir comment obtenir un ID de version, consultez la rubrique Lister des objets (SDK 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)

Définir des tags d'objet lors de la copie d'un objet

Vous pouvez utiliser l'une des méthodes suivantes pour configurer le tagging d'objet lors de la copie d'un objet :

  • Copie : le tag de l'objet source est copié vers l'objet de destination.

  • Remplacement : l'objet de destination reçoit le tag spécifié dans la requête, au lieu de celui de l'objet source.

Les exemples suivants expliquent comment ajouter des tags à un objet de moins de 1 Go en mode de copie simple, et à un objet de plus de 1 Go en mode de copie multipartie :

  • Ajouter des tags d'objet lors d'une copie simple

    Le code suivant montre comment définir des tags d'objet lors d'une copie simple d'un objet de moins de 1 Go.

    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()
  • Ajouter des tags d'objet lors d'une copie multipartie

    Le code suivant montre comment définir des tags d'objet lors d'une copie multipartie d'un objet de plus de 1 Go.

    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()

Définir des tags pour un lien symbolique

Le code suivant montre comment définir des tags pour un lien symbolique.

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()

Références

  • Pour obtenir l'exemple de code complet relatif à la définition de tags d'objet, consultez GitHub.

  • Pour plus d'informations sur l'opération API permettant de définir des tags d'objet, consultez la rubrique PutObjectTagging.