All Products
Search
Document Center

Object Storage Service:List objects

Last Updated:Sep 30, 2025

Objects in a bucket are sorted in lexicographical order by default. You can list all objects, list objects by directory, or adjust the number of objects returned per page.

List all objects

Use OSS SDKs

Java

For further instructions, see List objects (Java SDK).

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 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. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the maximum number of objects that can be listed at a time. 
        int maxKeys = 200;
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // Call the shutdown method to release resources when the OSSClient is no longer in use.  
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            String nextContinuationToken = null;
            ListObjectsV2Result result = null;

            // List objects by page by using the nextContinuationToken parameter included in the response of the previous list operation. 
            do {
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName).withMaxKeys(maxKeys);
                listObjectsV2Request.setContinuationToken(nextContinuationToken);
                result = ossClient.listObjectsV2(listObjectsV2Request);

                List<OSSObjectSummary> sums = result.getObjectSummaries();
                for (OSSObjectSummary s : sums) {
                    System.out.println("\t" + s.getKey());
                }

                nextContinuationToken = result.getNextContinuationToken();

            } while (result.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();
            }
        }
    }
}

Python

For further instructions, see List objects (Python SDK V2).

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="list objects v2 sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration to the one specified in the command line.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Create a paginator to allow the ListObjectsV2 operation to list objects.
    paginator = client.list_objects_v2_paginator()

    # Traverse each page of the listed objects.
    for page in paginator.iter_page(oss.ListObjectsV2Request(
            bucket=args.bucket
        )
    ):
        # Traverse each object on each page.
        for o in page.contents:
            # Display the name, size, and last modified time of the object.
            print(f'Object: {o.key}, {o.size}, {o.last_modified}')

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Go

For further instructions, see List objects (Go SDK V2).

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to list objects.
	request := &oss.ListObjectsV2Request{
		Bucket: oss.Ptr(bucketName),
	}

	// Create a paginator.
	p := client.NewListObjectsV2Paginator(request)

	// Initialize the page number counter.
	var i int
	log.Println("Objects:")

	// Traverse each page in the paginator.
	for p.HasNext() {
		i++

		// Obtain the data on the next page.
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}

		// Display information about each object on the page.
		for _, obj := range page.Contents {
			log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
		}
	}
}

PHP

For further instructions, see List objects (PHP SDK V2).

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If the required parameters are not configured, exit the program.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a Paginator object to list objects by page.
// List objects by page by using the ListObjectsV2Paginator object.
$paginator = new Oss\Paginator\ListObjectsV2Paginator(client: $client);
$iter = $paginator->iterPage(new Oss\Models\ListObjectsV2Request(bucket: $bucket)); // Initialize the paginator.

// Traverse the listed objects.
foreach ($iter as $page) {
    foreach ($page->contents ??  [] as $object) {
        // Display information about each object on the page.
        // Display the name, type, and size of each object.
        print("Object: $object->key, $object->type, $object->size\n");
    }
}

C#

For further instructions, see List objects (C# SDK V2).

using OSS = AlibabaCloud.OSS.V2;  // Create an alias for Alibaba Cloud OSS SDK to simplify subsequent use

var region = "cn-hangzhou";  // Required. Set the region where the bucket is located. For example, if the bucket is located in China (Hangzhou), set the region to cn-hangzhou
var endpoint = null as string;  // Optional. Specify the domain name to access the OSS service. For example, if the bucket is located in China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com
var bucket = "your bucket name";  // Required. The name of the target bucket

// Load the default configuration of the OSS SDK, which automatically reads credential information (such as AccessKey) from environment variables
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set to use environment variables to obtain credentials for authentication (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the bucket region in the configuration
cfg.Region = region;   
// If an endpoint is specified, override the default endpoint
if(endpoint != null) 
{
    cfg.Endpoint = endpoint;
} 

// Create an OSS client instance using the configuration information
using var client = new OSS.Client(cfg); 

// Call the ListObjectsV2Paginator method to obtain all objects in the target bucket
var paginator = client.ListObjectsV2Paginator(new OSS.Models.ListObjectsV2Request()
{
    Bucket = bucket
});

// Output information about all objects in the bucket
Console.WriteLine("Objects:");
await foreach (var page in paginator.IterPageAsync())  // Asynchronously iterate through each page of results
{
    // Iterate through each object on the current page
    foreach (var content in page.Contents ?? [])
    {
        // Output object information: name, size (bytes), last modified time
        Console.WriteLine($"Object:{content.Key}, {content.Size}, {content.LastModified}");
    }
}

Node.js

For further instructions, see List objects (Node.js).

const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of the bucket. 
  bucket: 'yourbucketname'
});

async function list () {
  let continuationToken = null;
  // List up to 20 objects on each page. 
  const maxKeys = 20;
  do {
    const result = await client.listV2({
      'continuation-token': continuationToken,
      'max-keys': maxKeys
      });
    continuationToken = result.nextContinuationToken;
        console.log(result);
  }while(continuationToken)
}

list();

Harmony

For further instructions, see List objects.

import Client, { RequestError } from '@aliyun/oss';

// Create an OSSClient instance.
const client = new Client({
  // Specify the AccessKey ID of the RAM user.
  accessKeyId: 'yourAccessKeyId',
  // Specify the AccessKey secret of the RAM user.
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});


/**
 * List objects in a bucket by page. 
 * Use the listObjectsV2 method and specify the continuationToken parameter to list objects by page. 
 */
const listObjectsV2WithContinuationToken = async () => {
  try {
    let continuationToken: string | undefined; // Specify the token for the next page, which is empty by default.
    let isTruncated=true; // Specifies whether the list result is truncated.

    // Traverse and list objects.
    while (isTruncated) {
      const res = await client.listObjectsV2({
        bucket: 'yourBucketName', // Specify the name of the bucket.
        continuationToken, // Specify the token for the next page.
      });

      // Display the objects and their metadata on this page.
      console.log(JSON.stringify(res));

      // Update the paging status.
      isTruncated = res.data.isTruncated; // Specifies whether the list result is truncated.
      continuationToken = res.data.nextContinuationToken; // Specify the token for the next page.
    }
  } catch (err) {
    // Capture exceptions during the request.
    if (err instanceof RequestError) {
      console.log('code: ', err.code); // The error code.
      console.log('message: ', err.message); // The error message.
      console.log('requestId: ', err.requestId); // The request ID.
      console.log('status: ', err.status); // The HTTP status code.
      console.log('ec: ', err.ec); // The EC.
    } else {
      console.log('unknown error: ', err);
    }
  }
};

// Call the listObjectsV2WithContinuationToken function to list objects by page.
listObjectsV2WithContinuationToken();

Swift

For further instructions, see List objects.

import AlibabaCloudOSS
import Foundation
@main
struct Main {
    static func main() async {
        do {
            // Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
            let region = "cn-hangzhou"
            // Specify the bucket name.
            let bucket = "yourBucketName"
            // Optional. Specify the endpoint for accessing the OSS service. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com
            let endpoint: String? = nil
            
            // Obtain a credential from the 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.
            let credentialsProvider = EnvironmentCredentialsProvider()
            // Configure OSS client parameters
            let config = Configuration.default()
                .withRegion(region)        // Set the region where the bucket is located
                .withCredentialsProvider(credentialsProvider)  // Set the access credential
                
            // Set the endpoint
            if let endpoint = endpoint {
                config.withEndpoint(endpoint)
            }
            
            // Create an OSS client instance
            let client = Client(config)
            // Create a paginator request object to traverse all objects in the bucket (paging processing)
            let paginator = client.listObjectsV2Paginator(
                ListObjectsV2Request(
                    bucket: bucket // Specify the bucket name for listing objects
                )
            )
            // Traverse the paging results and obtain object information page by page
            for try await page in paginator {
                // Traverse the object list in the current page
                for content in page.contents ?? [] {
                    // Output object metadata: object name, size (bytes), and last modified time
                    print("Object key:\(content.key ?? ""), size: \(String(describing: content.size)), last modified: \(String(describing: content.lastModified))")
                }
            }
        } catch {
            // Error output
            print("error:\(error)")
        }
    }
}

Ruby

For further instructions, see List objects.

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # 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. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

# Specify the name of the bucket. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')
# List all objects in the bucket. 
objects = bucket.list_objects
objects.each { |o| puts o.key }     

Browser.js

For further instructions, see List objects.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
  </head>
  <body>
    <script>      
      const client = new OSS({
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
        region: "yourRegion",
        authorizationV4: true,
        // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // Specify the security token that you obtained from STS. 
        stsToken: 'yourSecurityToken',
        // Specify the name of the bucket. Example: examplebucket. 
        bucket: "examplebucket",
      });

      async function list(dir) {
        try {
          // By default, up to 1,000 objects are listed. 
          let result = await client.list();
          console.log(result);

          // The list operation continues from the last object that was stopped in the previous list operation. 
          if (result.isTruncated) {
            result = await client.list({ marker: result.nextMarker });
          }

          // List the objects whose names start with the prefix 'ex'. 
          result = await client.list({
            prefix: "ex",
          });
          console.log(result);

          // List all objects whose names start with the prefix 'ex' and are alphabetically after the 'example' object. 
          result = await client.list({
            prefix: "ex",
            marker: "example",
          });
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      }

      list();
    </script>
  </body>
</html>
          

Android

For further instructions, see List objects.

private String marker = null;
private boolean isCompleted = false;

// List all objects in the bucket by page. 
public void getAllObject() {
    do {
        OSSAsyncTask task = getObjectList();
        // Wait until NextMarker is returned for the preceding request. Set the marker parameter in the current request to the value of NextMarker returned in the response to the preceding request. You do not need to set marker in the first request. 
        // In this example, a loop is used to list objects by page. Therefore, a request can be sent only after the NextMarker value for the preceding request is returned. You can determine whether to wait for the NextMarker value returned for the preceding request. 
        task.waitUntilFinished();
    } while (!isCompleted);
}

// List objects on a page. 
public OSSAsyncTask getObjectList() {
    // Specify the name of the bucket. 
    ListObjectsRequest request = new ListObjectsRequest("examplebucket");
    // Specify the maximum number of objects that can be listed on each page. If you do not specify this parameter, up to 100 objects are returned. The maximum value that you can specify for MaxKeys is 1000. 
    request.setMaxKeys(20);
    request.setMarker(marker);

    OSSAsyncTask task = oss.asyncListObjects(request, new OSSCompletedCallback<ListObjectsRequest, ListObjectsResult>() {
        @Override
        public void onSuccess(ListObjectsRequest request, ListObjectsResult result) {
            for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
                Log.i("ListObjects", objectSummary.getKey());
            }
            // List objects on the last page. 
            if (!result.isTruncated()) {
                isCompleted = true;
                return;
            }
            // Obtain the marker value for the next request. 
            marker = result.getNextMarker();
        }

        @Override
        public void onFailure(ListObjectsRequest request, ClientException clientException, ServiceException serviceException) {
            isCompleted = true;
            // Handle request exceptions. 
            if (clientException != null) {
                // Handle client-side exceptions, such as network errors. 
                clientException.printStackTrace();
            }
            if (serviceException != null) {
                // Handle server-side exceptions. 
                Log.e("ErrorCode", serviceException.getErrorCode());
                Log.e("RequestId", serviceException.getRequestId());
                Log.e("HostId", serviceException.getHostId());
                Log.e("RawMessage", serviceException.getRawMessage());
            }
        }
    });
    return task;
}

C++

For further instructions, see List objects.

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* 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. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    std::string nextMarker = "";
    bool isTruncated = false; 
    do {
        /* List objects. */
        ListObjectsRequest request(BucketName);
        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;
            ShutdownSdk();
            return -1;  
        }
        else {
            for (const auto& object : outcome.result().ObjectSummarys()) {
                std::cout << "object"<<
                ",name:" << object.Key() <<
                ",size:" << object.Size() <<
                ",lastmodify time:" << object.LastModified() << std::endl;
            }      
        }
        nextMarker = outcome.result().NextMarker();
        isTruncated = outcome.result().IsTruncated();
    } while (isTruncated);

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

iOS

For further instructions, see List objects.

 do {
    OSSGetBucketRequest *getBucket = [OSSGetBucketRequest new];
    getBucket.bucketName = @"examplebucket";
    getBucket.marker = _marker;  // Accessing the _marker instance variable
    getBucket.maxKeys = 20;

    OSSTask *getBucketTask = [client getBucket:getBucket];
    [getBucketTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            OSSGetBucketResult *result = task.result;
            NSLog(@"Get bucket success!");
            NSLog(@"objects: %@", result.contents);
            if (result.isTruncated) {
                _marker = result.nextMarker;  // Update the _marker instance variable
                _isCompleted = NO;
            } else {
                _isCompleted = YES;
            }
        } else {
            _isCompleted = YES;
            NSLog(@"Get bucket failed, error: %@", task.error);
        }
        return nil;
    }];
    // Implement synchronous blocking to wait for the task to complete. 
    [getBucketTask waitUntilFinished];
} while (!_isCompleted);

C

For further instructions, see List objects.

#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* 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. */
    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 two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Specify 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 in main() to initialize global resources, such as network resources and memory resources. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t bucket;
    aos_status_t *resp_status = NULL; 
    oss_list_object_params_t *params = NULL;
    oss_list_object_content_t *content = NULL;
    int size = 0;
    char *line = NULL;
    char *prefix = "";
    char *nextMarker = "";
    aos_str_set(&bucket, bucket_name);
    params = oss_create_list_object_params(pool);
    /* Set the max_ret parameter to specify the maximum number of objects to return. */
    /* By default, a maximum of 1,000 objects can be listed at a time. If the number of objects to list exceed 1,000, only the first 1,000 objects in alphabetical order are returned. In the returned results, the value of truncated is true, and the value of next_marker is returned as the start point for the next query. */
    params->max_ret = 100;
    aos_str_set(&params->prefix, prefix);
    aos_str_set(&params->marker, nextMarker);
    printf("Object\tSize\tLastModified\n");
    /* List all objects. */
    do {
        resp_status = oss_list_object(oss_client_options, &bucket, params, NULL);
        if (!aos_status_is_ok(resp_status))
        {
            printf("list object failed\n");
            break;
        }
        aos_list_for_each_entry(oss_list_object_content_t, content, &params->object_list, node) {
            ++size;
            line = apr_psprintf(pool, "%.*s\t%.*s\t%.*s\n", content->key.len, content->key.data, 
                content->size.len, content->size.data, 
                content->last_modified.len, content->last_modified.data);
            printf("%s", line);
        }
        nextMarker = apr_psprintf(pool, "%.*s", params->next_marker.len, params->next_marker.data);
        aos_str_set(&params->marker, nextMarker);
        aos_list_init(&params->object_list);
        aos_list_init(&params->common_prefix_list);
    } while (params->truncated == AOS_TRUE);
    printf("Total %d\n", size);
    /* Release the memory pool. This operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

Use ossutil

The following example shows how to list information about all objects in examplebucket.

ossutil api list-objects-v2 --bucket examplebucket

For more information, see list-objects-v2 (get-bucket-v2).

Use the OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets.

  3. Go to the destination bucket and click Object Management > Objects.

    The page displays all objects in the bucket in a paginated list. By default, the console displays 50 objects per page, with a maximum of 500.

List all objects in a specific directory

To get a flat list of all objects within a directory, including its subdirectories, set the prefix parameter.

The prefix parameter returns a filtered list of objects, including only those whose Keys start with the specified string. Since OSS utilizes a flat storage structure with no physical folders, this simple filtering mechanism effectively emulates directory traversal, allowing you to retrieve all objects within a logical folder.

Use OSS SDKs

Java

For the complete sample code, see List objects (Java SDK).

// ...

// Key code: Set the prefix.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setPrefix("images/");  // Specify the prefix.
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);

// ...

Python

For the complete sample code, see List objects (Python SDK V2).

# ...

# Key code: Add the prefix parameter.
for page in paginator.iter_page(oss.ListObjectsV2Request(
    bucket='your-bucket',
    prefix='images/'  # Specify the prefix.
)):
# ...

Go

For the complete sample code, see List objects (Go SDK V2).

// ...
// Key code: Set the prefix.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Prefix: oss.Ptr("images/"), // List all objects with the specified prefix.
}
// ...

Node.js

For the complete sample code, see List objects (Node.js).

// ...

// Key code: Set the prefix.
const result = await client.listV2({
    prefix: 'images/'  // Specify the prefix.
});

// ...

Harmony

For the complete sample code, see List objects.

// ...

// Key code: Set the prefix.
const res = await client.listObjectsV2({
    bucket: 'yourBucketName',
    prefix: 'images/',  // Specify the prefix.
});

// ...

Ruby

For the complete sample code, see List objects.

# ...

# Key code: Set the prefix.
objects = bucket.list_objects(:prefix => 'images/')  # Specify the prefix.

# ...

Android

For the complete sample code, see List objects.

// ...

// Key code: Set the prefix.
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
request.setPrefix("images/");  // Specify the prefix.

// ...

C++

For the complete sample code, see List objects.

// ...

// Key code: Set the prefix.
ListObjectsRequest request(BucketName);
request.setPrefix("images/");  // Specify the prefix.

// ...

iOS

For the complete sample code, see List objects.

// ...

// Key code: Set the prefix.
getBucket.prefix = @"images/";  // Specify the prefix.

// ...

C

For the complete sample code, see List objects.

// ...

// Key code: Set the prefix.
char *prefix = "images/";  // Specify the prefix.
aos_str_set(&params->prefix, prefix);

// ...

Use ossutil

The following example shows how to list information about all objects with the prefix dir/ in examplebucket.

ossutil api list-objects-v2 --bucket examplebucket --prefix dir/

For more information, see list-objects-v2 (get-bucket-v2).

Sample output

Assume the bucket contains the following objects:

images/cat.jpg
images/dog.png
images/archive/old.zip
readme.txt

When you set prefix="images/" in your request, the following response is returned:

images/
images/archive/
images/archive/old.zip
images/cat.jpg
images/dog.png

List immediate objects and subdirectories in a specific directory

By adding the delimiter parameter (usually set to /) along with the prefix parameter, you can divide the results into two parts: Objects and CommonPrefixes (subdirectories).

The delimiter parameter groups objects by hierarchy. When it is present, OSS processes the results filtered by prefix in a second step:

  • Keys that do not contain / after the prefix are returned in the Objects list.

  • Keys that contain / after the prefix are grouped. The part of the key from the beginning up to the first occurrence of / is then returned in the CommonPrefixes list.

Use OSS SDKs

Java

For the complete sample code, see List objects (Java SDK).

// ...

// Key code: Set the separator.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setPrefix("images/");  // Specify the directory.
listObjectsV2Request.setDelimiter("/");     // Set the separator.
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);

// Traverse the objects in the current directory.
for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
    System.out.println("Object: " + objectSummary.getKey());
}

// Traverse the subdirectories.
for (String commonPrefix : result.getCommonPrefixes()) {
    System.out.println("Subdirectory: " + commonPrefix);
}

// ...

Python

For the complete sample code, see List objects (Python SDK V2).

# ...

# Key code: Add the delimiter parameter.
for page in paginator.iter_page(oss.ListObjectsV2Request(
    bucket=args.bucket,
    prefix="images/",  # Specify the directory.
    delimiter="/",     # Set the separator.
)):
    # Traverse the objects in the current directory.
    for file in page.contents:
        print(f'Object: {file.key}')
    
    # Traverse the subdirectories.
    for prefix in page.common_prefixes:
        print(f'Subdirectory: {prefix.prefix}')

# ...

Go

// ...

// Key code: Set the separator.
request := &oss.ListObjectsV2Request{
    Bucket:    oss.Ptr(bucketName),
    Prefix:    oss.Ptr("images/"),  // Specify the directory.
    Delimiter: oss.Ptr("/"),        // Set the separator.
}

// Traverse the objects in the current directory.
for _, obj := range lsRes.Contents {
    log.Printf("Object: %v\n", oss.ToString(obj.Key))
}

// Traverse the subdirectories.
for _, prefix := range lsRes.CommonPrefixes {
    log.Printf("Subdirectory: %v\n", *prefix.Prefix)
}

// ...

PHP

For the complete sample code, see List objects (PHP SDK V2).

// ...

// Key code: Create a paginator and set the delimiter to distinguish between objects and subdirectories.
$paginator = new Oss\Paginator\ListObjectsV2Paginator(client: $client);
$iter = $paginator->iterPage(new Oss\Models\ListObjectsV2Request(
    bucket: $bucket,
    prefix: "",
    delimiter: "/"
));

// Traverse the paginated results.
foreach ($iter as $page) {
    // Traverse contents to get the objects in the current directory.
    foreach ($page->contents ?? [] as $object) {
        echo "Object: " . $object->key . PHP_EOL;
    }

    // Traverse commonPrefixes to get the subdirectories.
    foreach ($page->commonPrefixes ?? [] as $prefixObject) {
        echo "Subdirectory: " . $prefixObject->prefix . PHP_EOL;
    }
}

// ...

Node.js

For the complete sample code, see List objects (Node.js).

// ...
// Key code: Set the separator.
const result = await client.listV2({
prefix: dir, // Specify the directory.
delimiter: '/' // Set the separator.
});
// Traverse the objects in the current directory.
if (result && result.objects) {
result.objects.forEach(obj => {
console.log('Object: %s', obj.name);
});
}
// Traverse the subdirectories.
if (result && result.prefixes) {
result.prefixes.forEach(subDir => {
console.log('Subdirectory: %s', subDir);
});
}
// ...

Harmony

For the complete sample code, see List objects.

// ...
// Key code: Set the separator.
const res = await client.listObjectsV2({
bucket: 'yourBucketName', // The bucket name.
prefix: 'images/', // Specify the directory.
delimiter: '/', // Set the separator.
});
// Traverse the objects in the current directory.
if (res && res.objects) {
res.objects.forEach(obj => {
console.log('Object:', obj.name);
});
}
// Traverse the subdirectories.
if (res && res.prefixes) {
res.prefixes.forEach(subDir => {
console.log('Subdirectory:', subDir);
});
}
// ...

Browser.js

For the complete sample code, see List objects.

// ...
// Key code: Set the separator.
let result = await client.list({
prefix: 'images/', // Specify the directory.
delimiter: "/", // Set the separator.
});
// Traverse the objects in the current directory.
result.objects.forEach(function (obj) {
console.log("Object: %s", obj.name);
});
// Traverse the subdirectories.
result.prefixes.forEach(function (subDir) {
console.log("Subdirectory: %s", subDir);
});
// ...

Ruby

For the complete sample code, see List objects.

// ...
// Key code: Set the separator.
objects = bucket.list_objects(prefix: 'images/', delimiter: '/')
// Traverse the objects in the current directory.
if obj.is_a?(Aliyun::OSS::Object)
puts "Object: #{obj.key}"
end
// Traverse the subdirectories.
if obj.is_a?(String) # Common Prefix
puts "Subdirectory: #{obj}"
end
// ...

C++

For the complete sample code, see List objects.

// ...
// Key code: Set the separator.
ListObjectsRequest request(BucketName);
request.setPrefix("images/"); // Specify the directory.
request.setDelimiter("/"); // Set the separator.
// Traverse the objects in the current directory.
for (const auto& object : outcome.result().ObjectSummarys()) {
std::cout << "Object:" << object.Key() << std::endl;
}
// Traverse the subdirectories.
for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
std::cout << "Subdirectory:" << commonPrefix << std::endl;
}
// ...

C

For the complete sample code, see List objects.

// ...
// Key code: Set the separator.
params = oss_create_list_object_params(pool);
aos_str_set(&params->prefix, "images/"); // Specify the directory.
aos_str_set(&params->delimiter, "/"); // Set the separator.
// Traverse the objects in the current directory.
aos_list_for_each_entry(oss_list_object_content_t, content, &params->object_list, node) {
printf("Object: %.*s\n", content->key.len, content->key.data);
}
// Traverse the subdirectories.
aos_list_for_each_entry(oss_list_object_common_prefix_t, commonPrefix, &params->common_prefix_list, node) {
printf("Subdirectory: %.*s\n", commonPrefix->prefix.len, commonPrefix->prefix.data);
}
// ...

Use ossutil

The following example shows how to list the immediate objects and subdirectories within the images/ directory of examplebucket.

ossutil api list-objects-v2 --bucket examplebucket --prefix images/ --delimiter /

For more information, see list-objects-v2 (get-bucket-v2).

Sample output

When you set both prefix="images/" and delimiter="/", the results are grouped:

Objects:
images/
images/cat.jpg
images/dog.png
Directories:
images/archive/

List objects after a specified position

Use the startAfter parameter (or marker in some older SDKs) to skip all object keys that appear before a specified key in lexicographical order.

Use OSS SDKs

Java

For the complete sample code, see List objects (Java SDK).

// ...

// Key code: Set the starting position.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setStartAfter("images/cat.jpg");  // Start listing after the specified object.
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);

// ...

Python

For the complete sample code, see List objects (Python SDK V2).

# ...

# Key code: Add the start_after parameter.
for page in paginator.iter_page(oss.ListObjectsV2Request(
    bucket=args.bucket,
    start_after="images/cat.jpg",  # Start listing after the specified object.
)):

# ...

Go

For the complete sample code, see List objects (Go SDK V2).

// ...

// Key code: Set the starting position.
request := &oss.ListObjectsV2Request{
    Bucket:     oss.Ptr(bucketName),
    StartAfter: oss.Ptr("images/cat.jpg"),  // Start listing after the specified object.
}

// ...

PHP

For the complete sample code, see List objects (PHP SDK V2).

// ...
// Key code: Set the starting position.
$paginator = new Oss\Paginator\ListObjectsV2Paginator(client: $client);
$iter = $paginator->iterPage(new Oss\Models\ListObjectsV2Request(
bucket: $bucket,
startAfter:"images/cat.jpg", // Specify the starting position for listing objects.
));
// ...

Ruby

For the complete sample code, see List objects.

# ...

# Key code: Set the marker (starting position).
objects = bucket.list_objects(:marker => 'images/cat.jpg')  # Start listing after the specified object.

# ...

Android

For the complete sample code, see List objects.

// ...

// Key code: Set the marker (starting position).
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
request.setMarker("images/cat.jpg");  // Start listing after the specified object.

// ...

C++

For the complete sample code, see List objects.

// ...

// Key code: Set the marker (starting position).
ListObjectsRequest request(BucketName);
request.setMarker("images/cat.jpg");  // Start listing after the specified object.

// ...

iOS

For the complete sample code, see List objects.

// ...

// Key code: Set the marker (starting position).
getBucket.marker = @"images/cat.jpg";  // Start listing after the specified object.

// ...

C

For the complete sample code, see List objects.

// ...

// Key code: Set the marker (starting position).
char *nextMarker = "images/cat.jpg";  // Start listing after the specified object.
aos_str_set(&params->marker, nextMarker);

// ...

Use ossutil

The following example shows how to list information about objects that appear after test.txt in examplebucket.

ossutil api list-objects-v2 --bucket examplebucket --start-after test.txt

For more information, see list-objects-v2 (get-bucket-v2).

Sample output:

Assume the bucket contains:

images/cat.jpg
images/dog.png
images/archive/old.zip
readme.txt

When you set start-after="images/cat.jpg", the output will not include "images/cat.jpg" or any objects that precede it in lexicographical order:

images/dog.png
readme.txt

Adjust the number of objects per page

The MaxKey parameter controls the number of objects returned in a single request. The default value is 100, and the maximum is 1,000.

Use OSS SDKs

Java

For the complete sample code, see List objects (Java SDK).

// ...

// Key code: Add the max_keys parameter to set the number of objects per page.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setMaxKeys(1000);  // Set the maximum number of objects per page to 1000.
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);

// ...

Python

For the complete sample code, see List objects (Python SDK V2).

# ...

# Key code: Add the max_keys parameter to set the number of objects per page.
for page in paginator.iter_page(oss.ListObjectsV2Request(
    bucket=args.bucket,
    max_keys=1000,  # Set the maximum number of objects per page to 1000.
)):

# ...

Go

For the complete sample code, see List objects (Go SDK V2).

// ...

// Key code: Add the max_keys parameter to set the number of objects per page.
request := &oss.ListObjectsV2Request{
    Bucket:  oss.Ptr(bucketName),
    MaxKeys: 1000,  // Set the maximum number of objects per page to 1000.
}

// ...

PHP

For the complete sample code, see List objects (PHP SDK V2).

// ...

// Key code: Create a paginator and use the maxKeys parameter to set the maximum number of objects returned per page.
$paginator = new Oss\Paginator\ListObjectsV2Paginator(client: $client);
$iter = $paginator->iterPage(new Oss\Models\ListObjectsV2Request(
                bucket: $bucket,
                maxKeys: 10, //The maximum number of objects to return for each listing.
            ));

// ...

Node.js

For the complete sample code, see List objects (Node.js).

// ...

// Key code: Add the max_keys parameter to set the number of objects per page.
const result = await client.listV2({
    "max-keys": 1000  // Set the maximum number of objects per page to 1000.
});

// ...

Android

For the complete sample code, see List objects.

// ...

// Key code: Add the max_keys parameter to set the number of objects per page.
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
request.setMaxKeys(1000);  // Set the maximum number of objects per page to 1000.

// ...

C++

For the complete sample code, see List objects.

// ...

// Key code: Add the max_keys parameter to set the number of objects per page.
ListObjectsRequest request(BucketName);
request.setMaxKeys(1000);  // Set the maximum number of objects per page to 1000.

// ...

iOS

For the complete sample code, see List objects.

// ...

// Key code: Add the max_keys parameter to set the number of objects per page.
getBucket.maxKeys = 1000;  // Set the maximum number of objects per page to 1000.

// ...

C

For the complete sample code, see List objects.

// ...

// Key code: Add the max_keys parameter to set the number of objects per page.
params->max_ret = 1000;  // Set the maximum number of objects per page to 1000.

// ...

Use ossutil

The following example shows how to list information about the first 100 objects with the prefix dir in examplebucket.

ossutil api list-objects-v2 --bucket examplebucket --prefix dir/ --max-keys 100

For more information, see list-objects-v2 (get-bucket-v2).

Sample output:

Assume the bucket contains:

images/cat.jpg
images/dog.png
images/archive/old.zip
readme.txt
  • If maxKeys is set to 2, all objects are returned in pages of 2.

    image

  • If maxKeys is set to 100, all objects are returned in pages of 100.

    image

Apply in production

Performance optimization

  • Increase the page size: Setting max-keys to its maximum value of 1,000 can significantly reduce the number of API calls, especially under good network conditions. However, consider memory usage to avoid loading too much data at once.

  • Process prefixes in parallel: If you have hundreds of thousands of objects or more, a simple sequential listing can be slow. In this case, improve listing speed by processing different logical directories (prefixes) in parallel, such as images/, documents/, and logs/.

  • Cache the directory structure: For directory structures that change infrequently, cache the listing results to reduce redundant API calls.

Cost control

  • Avoid frequent full scans: Periodically listing all objects in a large bucket can be costly. Consider these more cost-effective alternatives:

    • To regularly generate a complete object manifest, use the lower-cost Inventory. It is ideal for periodic, large-scale analysis.

    • To respond to object uploads or deletions in real time, use event notifications. It is more efficient and cost-effective than listing objects.

  • Configure pagination reasonably: A page size that is too small increases the number of API calls, while one that is too large can increase processing time and memory consumption for a single request.

Quotas and limitations

  • Maximum items per response: A single ListObjects or ListObjectsV2 request can return up to 1,000 object keys.

  • Sorting method: Only lexicographical sorting by object key is supported.

FAQ

Does OSS support listing a specified number of pages of objects?

No.

How do I list all objects in a specific directory?

To list all objects within a specific directory, including their names and directory structure, use the list-objects-v2 (get-bucket-v2) command of ossutil 2.0.

Is sorting by last modified time supported when listing objects?

No. If you need to sort objects by their last modified time, use data indexing.