Manage OSS directories

更新时间:
复制 MD 格式

OSS provides directories that simulate a folder structure, making it easier to organize, locate, and perform bulk operations on large numbers of objects.

How it works

OSS uses flat storage and does not have real folders. The directories in the console are generated from the / delimiter in object names.

For example, when you see the following hierarchy in the console:

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

The actual objects stored in OSS are:

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

Create a directory

Create a directory in the following ways:

  • Automatic creation: When you upload an object whose name contains a path, the corresponding directory is automatically created.

  • Manual creation: Creates a zero-byte object ending in / that serves as a directory placeholder.

    Console

    1. Log on to the OSS console. In the target bucket, navigate to Object Management > Objects.

    2. Click Create Directory.

    3. Enter a Directory Name and click OK.

      Directory names must follow these rules:

      • The directory name must be UTF-8 encoded and cannot contain emojis.

      • Forward slashes (/) are used in a directory name to indicate subdirectories. Use forward slashes (/) in a directory name to create a nested directory structure. The directory name cannot start with a forward slash (/) or a backslash (\). The directory name cannot contain consecutive forward slashes (//).

      • The subdirectory name cannot be two consecutive periods (..).

      • The directory name must be 1 to 254 characters in length.

    ossutil

    Create a directory named dir/ in the examplebucket bucket:

    ossutil mkdir oss://examplebucket/dir

    mkdir (create directory)

    SDK

    These examples create a directory using common SDKs. Other SDKs are covered in Introduction to OSS SDKs.

    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.PutObjectRequest;
    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. The directory name must end with a forward slash (/).
            String objectName = "exampledir/";
    
            // Create an OSSClient instance.
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            try {            
                String content = "";
    
                // Create a PutObjectRequest object.       
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
                
                // To set the storage class and access permission for the object during the upload, see the following sample code.
                // ObjectMetadata metadata = new ObjectMetadata();
                // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
                // metadata.setObjectAcl(CannedAccessControlList.Private);
                // putObjectRequest.setMetadata(metadata);
    
                // Upload the object.
                ossClient.putObject(putObjectRequest);
            } 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;
    }

    ossbrowser

    1. Install ossbrowser 2.0 and log on to ossbrowser 2.0.

    2. Go to the target bucket and click Create Directory.

    3. Enter a directory name and click Save.

Rename a directory

Renaming a directory is not atomic. It involves two steps:

  1. Copy: Recursively copy all objects from the source directory to a new destination directory.

  2. Delete: After you confirm that the copy operation is successful, permanently delete the source directory and all objects within it.

Important

Renaming copies and deletes every object in the directory. For large directories, this is time-consuming and incurs significant API call and data transfer costs. Evaluate the impact carefully before proceeding.

ossbrowser

ossbrowser automates the complex copy-and-delete workflow, letting you rename a directory in a single action. We recommend this method for most use cases.

  1. Install ossbrowser 2.0 and log on to ossbrowser 2.0.

  2. Select the directory, click image, and then choose Rename.

    image

  3. Enter a new directory name and click Confirm.

ossutil

With ossutil, manually perform the Copy and Delete steps:

  1. Copy objects
    Use the cp (Copy objects) command with the --recursive (-r) option to copy all content from the old-dir/ directory to the new-dir/ directory in the examplebucket bucket.

    ossutil cp oss://examplebucket/old-dir/ oss://examplebucket/new-dir/ -r
  2. (Optional) Verify the copy operation
    Use the ls (List resources) command to check the new directory and verify that all objects were copied successfully.

    ossutil ls oss://examplebucket/new-dir/
  3. Delete the source directory
    After confirming the copy was successful, use the rm (Delete objects) command with the --recursive (-r) option to delete the source directory old-dir/.

    Warning

    This operation permanently deletes the old-dir/ directory and all objects within it. This action cannot be undone. Proceed with caution.

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

SDK

Renaming a directory with an SDK requires combining these API calls:

API

Rename a directory by combining these API calls:

Delete a directory

Warning

Deleting a directory also deletes all its subdirectories and objects. Proceed with caution.

Console

  1. Log on to the OSS console.

  2. Go to the Object Management > Objects page of the target bucket.

  3. Select the directory that you want to delete and click Permanently Delete in the Actions column.

  4. In the dialog box that appears, click OK.

    Important

    Do not refresh or close the task list during the deletion. This may interrupt the task.

Ossutil

Delete the directory test/ from the examplebucket bucket:

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

rm (delete)

SDK

Delete a directory and all its objects by specifying a Prefix. For example, to delete the log directory from the examplebucket bucket, set Prefix to 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 {
        // 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.
        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 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, credentialsProvider);

        try {
            // Delete the directory and all objects in it.
            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;
}

Ossbrowser

  1. Install ossbrowser 2.0 and log on to ossbrowser 2.0.

  2. Select the directory and click the image icon.

  3. Choose Delete and then click Confirm Deletion.

API

For direct REST API access, call the DeleteObject operation. This requires manually calculating the request signature.

Query object count and size

Method 1: List objects on demand

This method is best for on-demand queries of directories with fewer than 10,000 objects.

  1. In the navigation pane on the left of the target bucket, choose Object Management > Objects.

  2. Click Statistics to the right of the target directory.

    filesize.jpg

Method 2: Periodically query with a bucket inventory

Best for periodic queries on directories with up to tens of billions of objects.

  1. In the navigation pane on the left of the target bucket, choose Data Management > Bucket Inventory.

  2. Click Create Inventory. In the Create Inventory panel, select a Inventory Storage Bucket. For inventory content, select Object Size. For prefix matching, enter the directory name (for example, random_files/). Leave the other parameters at their default settings.

    screenshot_2025-07-04_18-14-09

  3. View the inventory report.

    1. On the Objects page, find the generated inventory report file in the /Destination Bucket/inventory-id/data/ path.

      screenshot_2025-07-04_18-22-28

    2. Download the inventory report file to view the object count and total size for the directory.

      In the inventory report file, column A contains the bucket name, column B lists the name of each object, and column C shows the size of that object.

      screenshot_2025-07-04_18-28-44

The bucket inventory documentation covers setup and configuration details.

Method 3: Run complex queries with MetaSearch

Best for near-real-time queries that filter by prefix, time, or object type.

  1. In the navigation pane on the left of the target bucket, choose Object Management > Data Indexing.

  2. On the Data Indexing page, click Enable Now, select MetaSearch, and then click Enable.

    Note

    Enabling MetaSearch may take some time, depending on the number of objects in the bucket.

  3. Set Object Name to prefix match, enter random_files/ as the prefix, and keep the other parameters at their default settings.

    image

  4. Configure the output format.

    • Set Object Sort Order to Default.

    • For Data Aggregation, aggregate Object Size by Sum.

      image

  5. Click Query Now. The results show the total object count and total size for the random_files/ directory.

    image

The MetaSearch documentation covers setup and query options.

Production considerations

Access control

In OSS, access control is based on object prefix matching, not on the directory object itself.

For example, to grant a user read-only access to all objects in the logs/ directory:

  • Incorrect: Setting permissions on the zero-byte logs/ placeholder object.

  • Correct: Create a RAM policy where the Resource field is set to acs:oss:*:*:your-bucket-name/logs/*. This policy matches all objects that start with the logs/ prefix, regardless of whether the logs/ placeholder object exists.

Performance optimization

  • Directory depth: Avoid deeply nested structures, such as a/b/c/d/.../file.log, as the filtering logic for list operations can degrade performance.

  • Large-scale renames: Renaming a directory with many objects generates a high volume of API calls and significantly increases traffic costs. Avoid this practice in your system design.