Tous les produits
Search
Centre de documentation

Object Storage Service:Manage OSS directories

Dernière mise à jour :Sep 22, 2026

OSS propose des répertoires qui simulent une structure de dossiers, facilitant ainsi l'organisation, la localisation et l'exécution d'opérations groupées sur un grand nombre d'objets.

Fonctionnement

OSS utilise un stockage à plat et ne dispose pas de véritables dossiers. Les répertoires affichés dans la console sont générés à partir du délimiteur / présent dans les noms des objets.

Par exemple, lorsque vous observez la hiérarchie suivante dans la console :

examplebucket
    └── log/
       ├── date1.txt
       ├── date2.txt  
       ├── date3.txt
    └── destfolder/
       └── 2021/
          ├── photo.jpg

Les objets réellement stockés dans OSS sont les suivants :

log/date1.txt
log/date2.txt
destfolder/2021/photo.jpg

Créer un répertoire

Vous pouvez créer un répertoire de deux manières :

  • Création automatique : lorsque vous téléchargez un objet dont le nom contient un chemin d'accès, le répertoire correspondant est créé automatiquement.

  • Création manuelle : cette méthode crée un objet de zéro octet se terminant par / qui sert d'espace réservé pour le répertoire.

    Console

    1. Connectez-vous à la console OSS. Dans le bucket cible, accédez à Object Management > Objects.

    2. Cliquez sur Create Directory.

    3. Saisissez un Directory Name puis cliquez sur OK.

      Les noms de répertoire doivent respecter les règles suivantes :

      • Le nom du répertoire doit être encodé en UTF-8 et ne peut pas contenir d'emojis.

      • Les barres obliques (/) sont utilisées dans un nom de répertoire pour indiquer des sous-répertoires. Utilisez des barres obliques (/) dans un nom de répertoire pour créer une structure de répertoires imbriquée. Le nom du répertoire ne peut pas commencer par une barre oblique (/) ou une barre oblique inverse (\). Le nom du répertoire ne peut pas contenir de barres obliques consécutives (//).

      • Le nom du sous-répertoire ne peut pas être constitué de deux points consécutifs (..).

      • La longueur du nom du répertoire doit être comprise entre 1 et 254 caractères.

    ossutil

    Créez un répertoire nommé dir/ dans le bucket examplebucket :

    ossutil mkdir oss://examplebucket/dir

    mkdir (créer un répertoire)

    SDK

    Ces exemples illustrent la création d'un répertoire à l'aide de SDK courants. D'autres SDK sont décrits dans la rubrique Présentation des SDK OSS.

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import java.io.ByteArrayInputStream;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // Set the endpoint. The China (Hangzhou) region is used in this example. Specify the actual endpoint.
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // For security, do not hard-code access credentials. Leaked credentials can compromise all your resources. This example uses an environment variable for credentials. Ensure it is configured before running.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the bucket name, for example, examplebucket.
            String bucketName = "examplebucket";
            // Specify the directory name for Method 1.
            String dirName = "exampledir/";
            // Specify the directory name for Method 2.
            String dirName2 = "exampledir1/";
    
            // Create an OSSClient instance.
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            try {
                // Method 1: Create a directory by calling the createDirectory operation. Before you use this method, you must enable hierarchical namespace.
                ossClient.createDirectory(bucketName, dirName);
    
                // Method 2: Create a directory by uploading an empty string.
                ossClient.putObject(bucketName, dirName2, new ByteArrayInputStream("".getBytes()));
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
    <?php
    if (is_file(__DIR__ . '/../autoload.php')) {
        require_once __DIR__ . '/../autoload.php';
    }
    if (is_file(__DIR__ . '/../vendor/autoload.php')) {
        require_once __DIR__ . '/../vendor/autoload.php';
    }
    
    use OSS\Credentials\EnvironmentVariableCredentialsProvider;
    use OSS\OssClient;
    use OSS\CoreOssException;
    // Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    $provider = new EnvironmentVariableCredentialsProvider();
    // Specify the endpoint for your bucket's region. For example, use https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region.
    $endpoint = "yourEndpoint";
    // Specify the bucket name, for example, examplebucket.
    $bucket= "examplebucket";
    // Specify the directory name. The name must end with a forward slash (/).
    $object = "exampledir/";
    $content = "";
    try{
        $config = array(
            "provider" => $provider,
            "endpoint" => $endpoint,
        );
        $ossClient = new OssClient($config);
    
        $ossClient->putObject($bucket, $object, $content);
    } catch(OssException $e) {
        printf(__FUNCTION__ . ": FAILED\n");
        printf($e->getMessage() . "\n");
        return;
    }
    print(__FUNCTION__ . "OK" . "\n");
    
    // You can set headers when you upload an object, such as setting the access permission to private or specifying custom metadata.
    $options = array(
        OssClient::OSS_HEADERS => array(
            'x-oss-object-acl' => 'private',
            'x-oss-meta-info' => 'your info'
        ),
    );
    try{
        $config = array(
            "provider" => $provider,
            "endpoint" => $endpoint,
        );
        $ossClient = new OssClient($config);
    
        $ossClient->putObject($bucket, $object, $content, $options);
    } catch(OssException $e) {
        printf(__FUNCTION__ . ": FAILED\n");
        printf($e->getMessage() . "\n");
        return;
    }
    print(__FUNCTION__ . "OK" . "\n");           
    const OSS = require('ali-oss');
    
    const client = new OSS({
      // Specify the region where your bucket is located. For example, use 'oss-cn-hangzhou' for the China (Hangzhou) region.
      region: 'yourregion',
      // Obtain access credentials from environment variables. Before you run this example, 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,
      // Specify the bucket name.
      bucket: 'examplebucket',
    });
    
    async function putBuffer () {
      try {
        // Specify the directory name. The name must end with a forward slash (/).
        const result = await client.put('exampledir/', new Buffer(''));
        console.log(result);
      } catch (e) {
        console.log(e);
      }
    }
    
    putBuffer();
    # -*- coding: utf-8 -*-
    
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
    # Specify the endpoint for your bucket's region. For example, use https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region.
    # Specify the bucket name.
    bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
    
    # Specify the directory name. The name must end with a forward slash (/).
    bucket.put_object('exampledir/', '')    
    using System.Text;
    using Aliyun.OSS;
    
    // Specify the endpoint for your bucket's region. For example, use https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region.
    var endpoint = "yourEndpoint";
    // Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
    var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
    // Specify the bucket name, for example, examplebucket.
    var bucketName = "examplebucket";
    // Specify the directory name. The name must end with a forward slash (/).
    var objectName = "exampledir/";
    var objectContent = "";
    
    // Create an OssClient instance.
    var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
    try
    {
        byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
        MemoryStream requestContent = new MemoryStream(binaryData);
        // Create the directory.
        client.PutObject(bucketName, objectName, requestContent);
        Console.WriteLine("Put object succeeded");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Put object failed, {0}", ex.Message);
    }
    #include "oss_api.h"
    #include "aos_http_io.h"
    /* Specify the endpoint for your bucket's region. For example, use https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region. */
    const char *endpoint = "yourEndpoint";
    
    /* Specify the bucket name, for example, examplebucket. */
    const char *bucket_name = "examplebucket";
    /* Specify the directory name. The name must end with a forward slash (/). */
    const char *object_name = "exampledir/";
    const char *object_content = "";
    void init_options(oss_request_options_t *options)
    {
        options->config = oss_config_create(options->pool);
        /* Initialize the aos_string_t type with a char* string. */
        aos_str_set(&options->config->endpoint, endpoint);
        /* Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */    
        aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
        aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
        /* Specify whether a CNAME is used. 0 indicates that no CNAME is used. */
        options->config->is_cname = 0;
        /* Set network parameters, such as the timeout period. */
        options->ctl = aos_http_controller_create(options->pool, 0);
    }
    int main(int argc, char *argv[])
    {
        /* Call the aos_http_io_initialize method at program startup to initialize global resources, such as the network and memory. */
        if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
            exit(1);
        }
        /* The memory pool (pool), which is equivalent to apr_pool_t, is used for memory management. It is implemented in the apr library. */
        aos_pool_t *pool;
        /* Create a memory pool. The second parameter is NULL, which indicates that the memory pool does not inherit from another memory pool. */
        aos_pool_create(&pool, NULL);
        /* Create and initialize options. This parameter includes global configuration information such as the endpoint, access_key_id, access_key_secret, is_cname, and curl. */
        oss_request_options_t *oss_client_options;
        /* Allocate memory for options from the memory pool. */
        oss_client_options = oss_request_options_create(pool);
        /* Initialize the client option oss_client_options. */
        init_options(oss_client_options);
        /* Initialize parameters. */
        aos_string_t bucket;
        aos_string_t object;
        aos_list_t buffer;
        aos_buf_t *content = NULL;
        aos_table_t *headers = NULL;
        aos_table_t *resp_headers = NULL; 
        aos_status_t *resp_status = NULL; 
        aos_str_set(&bucket, bucket_name);
        aos_str_set(&object, object_name);
        aos_list_init(&buffer);
        content = aos_buf_pack(oss_client_options->pool, object_content, strlen(object_content));
        aos_list_add_tail(&content->node, &buffer);
        /* Upload the object. */
        resp_status = oss_put_object_from_buffer(oss_client_options, &bucket, &object, &buffer, headers, &resp_headers);
        /* Check whether the upload is successful. */
        if (aos_status_is_ok(resp_status)) {
            printf("put object from buffer succeeded\n");
        } else {
            printf("put object from buffer failed\n");      
        }
        /* Destroy the memory pool. This releases the memory allocated to resources during the request. */
        aos_pool_destroy(pool);
        /* Release the previously allocated global resources. */
        aos_http_io_deinitialize();
        return 0;
    }

Renommer un répertoire

Le renommage d'un répertoire n'est pas atomique. Il implique deux étapes :

  1. Copie : copiez récursivement tous les objets du répertoire source vers un nouveau répertoire de destination.

  2. Suppression : après avoir confirmé que l'opération de copie a réussi, supprimez définitivement le répertoire source et tous les objets qu'il contient.

Important

Le renommage copie et supprime chaque objet du répertoire. Pour les répertoires volumineux, cette opération prend du temps et engendre des coûts importants liés aux appels API et au transfert de données. Évaluez attentivement l'impact avant de procéder.

  • Si l'espace de noms hiérarchique est activé sur votre bucket, vous pouvez renommer directement un répertoire.

    Console

    1. Connectez-vous à la console OSS.

    2. Dans le volet de navigation de gauche, cliquez sur Buckets. Sur la page Buckets, recherchez le bucket souhaité et cliquez dessus.

    3. Dans le volet de navigation de gauche, choisissez Object Management > Objects.

    4. Renommez ou déplacez le répertoire.

      Supprimez un répertoire en spécifiant son nom pour l'option prefix de la commande ossutil rm. rm (supprimer)

      Scénario

      Actions

      Renommer un répertoire

      Survolez le répertoire cible et cliquez sur l'icône edit pour renommer le répertoire. Le nom du répertoire ne peut pas commencer par une barre oblique /.

      Déplacer un répertoire

      Le déplacement d'un répertoire est similaire à son renommage, mais le nouveau nom de répertoire doit commencer par une barre oblique (/). Spécifiez le répertoire cible en fonction de l'un des scénarios suivants :

      • Si vous souhaitez déplacer le sous-répertoire subdir du répertoire parent destdir vers un autre répertoire parent destfolder, saisissez /destfolder/subdir comme nouveau nom de répertoire.

      • Si vous souhaitez déplacer le sous-répertoire subdir du répertoire parent destdir vers le répertoire racine du bucket, saisissez /subdir comme nouveau nom de répertoire.

    SDK

    Le renommage des répertoires n'est pris en charge qu'avec la version 3.12.0 ou ultérieure du SDK Java.

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
            String endPoint = "yourEndpoint";
            // Avoid hard-coding access credentials, as leaked credentials can compromise your resources. This example obtains credentials from environment variables. Ensure the variables are configured before running the code.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the bucket name. Example: examplebucket.
            String bucketName = "examplebucket";
            // Specify the absolute path of the source directory. The absolute path cannot contain the bucket name.
            String sourceDir = "exampledir";
            // Specify the absolute path of the destination directory, which must be in the same bucket as the source directory. The absolute path cannot contain the bucket name.
            String destinationDir = "newexampledir";
    
            // Create an OSSClient instance.
            OSS ossClient = new OSSClientBuilder().build(endPoint, credentialsProvider);
    
            try {
                // Rename the source directory in the bucket to the destination directory.
                RenameObjectRequest renameObjectRequest = new RenameObjectRequest(bucketName, sourceDir, destinationDir);
                ossClient.renameObject(renameObjectRequest);
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

    API

    Pour un accès direct via l'API REST, appelez RenameObject. Cela nécessite le calcul manuel de la signature de la requête.

  • Si l'espace de noms hiérarchique est désactivé, vous devez renommer un répertoire en listant tous les objets qu'il contient, en les copiant vers un nouveau préfixe, puis en supprimant les objets d'origine.

    Remarque

    Pour copier par lot un grand nombre d'objets, utilisez Data Online Migration. Pour plus d'informations, consultez la rubrique Migrer des données entre des buckets OSS.

    ossutil

    Avec ossutil, effectuez manuellement les étapes Copie et Suppression :

    1. Copier les objets : utilisez la commande cp (copier des objets) avec l'option --recursive (-r) pour copier tout le contenu du répertoire old-dir/ vers le répertoire new-dir/ dans le bucket examplebucket.

      ossutil cp oss://examplebucket/old-dir/ oss://examplebucket/new-dir/ -r
    2. (Facultatif) Vérifier l'opération de copie : utilisez la commande ls (lister les ressources) pour vérifier le nouveau répertoire et vous assurer que tous les objets ont été copiés avec succès.

      ossutil ls oss://examplebucket/new-dir/
    3. Supprimer le répertoire source : après avoir confirmé que la copie a réussi, utilisez la commande rm (supprimer des objets) avec l'option --recursive (-r) pour supprimer le répertoire source old-dir/.

      Avertissement

      Cette opération supprime définitivement le répertoire old-dir/ et tous les objets qu'il contient. Cette action est irréversible. Procédez avec prudence.

      ossutil rm oss://examplebucket/old-dir/ -r

    SDK

    Le renommage d'un répertoire avec un SDK nécessite de combiner ces appels API :

    API

    Renommez un répertoire en combinant ces appels API :

Supprimer un répertoire

Avertissement

La suppression d'un répertoire entraîne également la suppression de tous ses sous-répertoires et objets. Procédez avec prudence.

Console

  1. Connectez-vous à la console OSS.

  2. Accédez à la page Object Management > Objects du bucket cible.

  3. Sélectionnez le répertoire que vous souhaitez supprimer et cliquez sur Permanently Delete dans la colonne Actions.

  4. Dans la boîte de dialogue qui s'affiche, cliquez sur OK.

    Important

    Ne rafraîchissez pas et ne fermez pas la liste des tâches pendant la suppression. Cela pourrait interrompre la tâche.

Ossutil

Supprimez le répertoire test/ du bucket examplebucket :

ossutil rm oss://examplebucket/test/ -r

rm (delete)

SDK

Supprimez un répertoire et tous ses objets en spécifiant un Prefix. Par exemple, pour supprimer le répertoire log du bucket examplebucket, définissez Prefix sur log/.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class Demo {

    public static void main(String[] args) throws Exception {
        // The endpoint for the China (Hangzhou) region is used as an example. Specify the endpoint for your bucket's region.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Avoid hard-coding access credentials in your code to prevent security risks from leaks. This example loads credentials from environment variables. Ensure these variables are configured before running the code.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the absolute path of the directory. The path cannot contain the bucket name.
        String directoryName = "exampledir";
        // Specify the full path of the directory to be deleted. The path cannot contain the bucket name.
        final String prefix = "log/";

        // Create an OSSClient instance.
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Method 1: Recursively delete the directory by calling the deleteDirectory operation. Before you use this method, you must enable the hierarchical namespace feature.
            DeleteDirectoryRequest deleteDirectoryRequest = new DeleteDirectoryRequest(bucketName, directoryName);
            deleteDirectoryRequest.setDeleteRecursive(true);
            DeleteDirectoryResult deleteDirectoryResult = ossClient.deleteDirectory(deleteDirectoryRequest);

            // View the deletion result.
            // A maximum of 100 directories and objects can be deleted at a time. If the deletion is incomplete, the server returns a `nextDeleteToken`. Use this token to continue deleting the remaining items.
            // The nextDeleteToken parameter specifies the starting point for the next deletion.
            String nextDeleteToken = deleteDirectoryResult.getNextDeleteToken();
            System.out.println("delete next token:" + nextDeleteToken);
            // The absolute path of the deleted directory.
            System.out.println("delete dir name :" + deleteDirectoryResult.getDirectoryName());
            // The total number of objects and directories that are deleted in this operation.
            System.out.println("delete number:" + deleteDirectoryResult.getDeleteNumber());

            // Method 2: Delete the directory and all objects in it by iterating through the results returned by the listObjects operation.
            String nextMarker = null;
            ObjectListing objectListing = null;
            do {
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName)
                        .withPrefix(prefix)
                        .withMarker(nextMarker);

                objectListing = ossClient.listObjects(listObjectsRequest);
                if (objectListing.getObjectSummaries().size() > 0) {
                    List<String> keys = new ArrayList<String>();
                    for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
                        System.out.println("key name: " + s.getKey());
                        keys.add(s.getKey());
                    }
                    DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url");
                    DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
                    List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
                    try {
                        for(String obj : deletedObjects) {
                            String deleteObj =  URLDecoder.decode(obj, "UTF-8");
                            System.out.println(deleteObj);
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                nextMarker = objectListing.getNextMarker();
            } while (objectListing.isTruncated());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
   require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
   require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;
// This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Specify the endpoint for your bucket's region. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "your-endpoint";
// Specify the bucket name.
$bucket = "examplebucket";

try {
   $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
   $option = array(
      OssClient::OSS_MARKER => null,
      // Specify the full path of the directory to be deleted. The path cannot contain the bucket name.
      OssClient::OSS_PREFIX => "log/",
      OssClient::OSS_DELIMITER=>'',
   );
   $bool = true;
   while ($bool){
      $result = $ossClient->listObjects($bucket,$option);
      $objects = array();
      if(count($result->getObjectList()) > 0){
         foreach ($result->getObjectList() as $key => $info){
            printf("key name:".$info->getKey().PHP_EOL);
            $objects[] = $info->getKey();
         }
         // Delete the directory and all objects in it.
         $delObjects = $ossClient->deleteObjects($bucket, $objects);
         foreach ($delObjects as $info){
            $obj = strval($info);
            printf("Delete ".$obj." : Success" . PHP_EOL);
         }
      }

      if($result->getIsTruncated() === 'true'){
         $option[OssClient::OSS_MARKER] = $result->getNextMarker();
      }else{
         $bool = false;
      }
   }
   printf("Delete Objects : OK" . PHP_EOL);
} catch (OssException $e) {
   printf("Delete Objects : Failed" . PHP_EOL);
   printf($e->getMessage() . PHP_EOL);
   return;
}
const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region where your bucket is located. For example, for the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'yourregion',
  // This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the bucket name.
  bucket: 'yourbucketname'
});

// Handle a failed request to prevent `promise.all` from being interrupted. Returns the failure reason and the name of the object that failed to be deleted.
async function handleDel(name, options) {
  try {
    await client.delete(name);
  } catch (error) {
    error.failObjectName = name;
    return error;
  }
}

// Delete multiple objects.
async function deletePrefix(prefix) {
  const list = await client.list({
    prefix: prefix,
  });

  list.objects = list.objects || [];
  const result = await Promise.all(list.objects.map((v) => handleDel(v.name)));
  console.log(result);
}
// Delete the directory and all objects in it.
deletePrefix('log/')
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Set your endpoint to the endpoint of the region where your bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the bucket name.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
prefix = "exampledir/"

# Delete the directory and all objects in it.
for obj in oss2.ObjectIterator(bucket, prefix=prefix):
    bucket.delete_object(obj.key)
package main

import (
    "fmt"
    "os"

    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance.
    // Specify the endpoint for the region where your bucket is located. For example, the endpoint for the China (Hangzhou) region is `https://oss-cn-hangzhou.aliyuncs.com`. Replace this with the endpoint for your actual region.
    client, err := oss.New("your-endpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Specify the bucket name.
    bucket, err := client.Bucket("examplebucket")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    
    marker := oss.Marker("")
    // Specify the full path of the directory to be deleted. The path cannot contain the bucket name.
    prefix := oss.Prefix("log/")
    count := 0
    for {
        lor, err := bucket.ListObjects(marker, prefix)
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }

        objects := []string{}
        for _, object := range lor.Objects {
            objects = append(objects, object.Key)
        }
        // Delete the directory and all objects in it.
        // Set `oss.DeleteObjectsQuiet` to `true` to suppress the deletion results.
        delRes, err := bucket.DeleteObjects(objects, oss.DeleteObjectsQuiet(true))
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }

        if len(delRes.DeletedObjects) > 0 {
            fmt.Println("These objects failed to delete:", delRes.DeletedObjects)
            os.Exit(-1)
        }

        count += len(objects)

        prefix = oss.Prefix(lor.Prefix)
        marker = oss.Marker(lor.NextMarker)
        if !lor.IsTruncated {
            break
        }
    }
    fmt.Printf("success,total delete object count:%d\n", count)
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
            
    /* Specify the endpoint for the region where your bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "your-endpoint";
    /* Specify the bucket name. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the directory to be deleted. The path cannot contain the bucket name. */
    std::string keyPrefix = "log/";

    /* Initialize resources, such as the network. */
    InitializeSdk();

    ClientConfiguration conf;
    /* This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    std::string nextMarker = "";
    bool isTruncated = false;
    do {            
            ListObjectsRequest request(BucketName);            
            request.setPrefix(keyPrefix);
            request.setMarker(nextMarker);
            auto outcome = client.ListObjects(request);

            if (!outcome.isSuccess()) {
                /* Handle exceptions. */
                std::cout << "ListObjects fail" <<
                ",code:" << outcome.error().Code() <<
                ",message:" << outcome.error().Message() <<
                ",requestId:" << outcome.error().RequestId() << std::endl;
                break;
            }
            for (const auto& object : outcome.result().ObjectSummarys()) {
                DeleteObjectRequest request(BucketName, object.Key());
                /* Delete the directory and all objects in it. */
                auto delResult = client.DeleteObject(request);
            }
            nextMarker = outcome.result().NextMarker();
            isTruncated = outcome.result().IsTruncated();
    } while (isTruncated);

    /* Release resources, such as the network. */
    ShutdownSdk();
    return 0;
}

API

Pour un accès direct via l'API REST, appelez l'opération DeleteObject . Cela nécessite de calculer manuellement la signature de la requête.

Interroger le nombre d'objets et la taille

Méthode 1 : Lister les objets à la demande

Cette méthode est idéale pour les requêtes ponctuelles concernant des répertoires contenant moins de 10 000 objets.

  1. Dans le volet de navigation de gauche du bucket cible, choisissez Object Management > Objects.

  2. Cliquez sur Statistics à droite du répertoire cible.

Méthode 2 : Interroger périodiquement avec un inventaire de bucket

Idéale pour les requêtes périodiques sur des répertoires contenant jusqu'à des dizaines de milliards d'objets.

  1. Dans le volet de navigation de gauche du bucket cible, choisissez Data Management > Bucket Inventory.

  2. Cliquez sur Create Inventory. Dans le panneau Create Inventory, sélectionnez un Inventory Storage Bucket. Pour le contenu de l'inventaire, sélectionnez Object Size. Pour la correspondance de préfixe, saisissez le nom du répertoire (par exemple, random_files/). Laissez les autres paramètres avec leurs valeurs par défaut.

  3. Consultez le rapport d'inventaire.

    1. Sur la page Objects, recherchez le fichier de rapport d'inventaire généré dans le chemin /Destination Bucket/inventory-id/data/.

    2. Téléchargez le fichier de rapport d'inventaire pour afficher le nombre d'objets et la taille totale du répertoire.

      Dans le fichier de rapport d'inventaire, la colonne A contient le nom du bucket, la colonne B répertorie le nom de chaque objet et la colonne C indique la taille de cet objet.

La documentation sur l'inventaire de bucket couvre les détails de la configuration.

Méthode 3 : Exécuter des requêtes complexes avec MetaSearch

Idéale pour les requêtes en temps quasi réel qui filtrent par préfixe, heure ou type d'objet.

  1. Dans le volet de navigation de gauche du bucket cible, choisissez Object Management > Data Indexing.

  2. Sur la page Data Indexing, cliquez sur Enable Now, sélectionnez MetaSearch, puis cliquez sur Enable.

    Remarque

    L'activation de MetaSearch peut prendre un certain temps, selon le nombre d'objets dans le bucket.

  3. Définissez Object Name sur la correspondance de préfixe, saisissez random_files/ comme préfixe et conservez les autres paramètres avec leurs valeurs par défaut.

  4. Configurez le format de sortie.

    • Définissez Object Sort Order sur Default.

    • Pour Data Aggregation, agrégez Object Size par Sum.

  5. Cliquez sur Query Now. Les résultats affichent le nombre total d'objets et la taille totale du répertoire random_files/.

    Les résultats de la requête indiquent que dans Data Aggregation, la somme des tailles de fichiers est de 14,47 Go. Dans la section Objects, chaque fichier a une taille de 50 Mo, le type de téléchargement est Normal, la classe de stockage est Standard et la liste de contrôle d'accès (ACL) est héritée du bucket.

La documentation sur MetaSearch couvre la configuration et les options de requête.

Considérations pour la production

Contrôle d'accès

Dans OSS, le contrôle d'accès repose sur la correspondance du préfixe d'objet, et non sur l'objet répertoire lui-même.

Par exemple, pour accorder à un utilisateur un accès en lecture seule à tous les objets du répertoire logs/ :

  • Incorrect : Définir les autorisations sur l'objet espace réservé logs/ de zéro octet.

  • Correct : Créez une politique RAM où le champ Resource est défini sur acs:oss:*:*:your-bucket-name/logs/*. Cette politique correspond à tous les objets commençant par le préfixe logs/, que l'objet espace réservé logs/ existe ou non.

Optimisation des performances

  • Profondeur des répertoires : Évitez les structures profondément imbriquées, telles que a/b/c/d/.../file.log, car la logique de filtrage pour les opérations de liste peut dégrader les performances.

  • Renommages à grande échelle : Le renommage d'un répertoire contenant de nombreux objets génère un volume élevé d'appels d'API et augmente considérablement les coûts de trafic. Évitez cette pratique dans la conception de votre système.