Objects in a bucket are sorted lexicographically by default. You can list all objects, list objects by directory, or adjust the number of objects returned per page.
List all objects
This operation lists all objects in a bucket.
SDK
Java
For more information, see List objects (Java SDK V1).
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 more information, 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 more information, 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(®ion, "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 more information, 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 more information, 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 more information, 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 more information, see List objects (Harmony SDK).
import Client, { RequestError } from '@aliyun/oss';
// Create an OSS client instance.
const client = new Client({
// Replace with the AccessKey ID of your RAM user.
accessKeyId: 'yourAccessKeyId',
// Replace with the AccessKey secret of your RAM user.
accessKeySecret: 'yourAccessKeySecret',
// Set the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to 'oss-cn-hangzhou'.
region: 'oss-cn-hangzhou',
});
/**
* List objects in a bucket page by page.
* Use the listObjectsV2 method with the continuationToken parameter to list objects page by page.
*/
const listObjectsV2WithContinuationToken = async () => {
try {
let continuationToken: string | undefined; // The pagination token. It is initially empty.
let isTruncated = true; // Indicates whether there are more objects to list.
// Loop through and list objects until no more objects are left.
while (isTruncated) {
const res = await client.listObjectsV2({
bucket: 'yourBucketName', // The bucket name. Replace with the name of your bucket.
continuationToken, // The pagination token used to retrieve the next page of results.
});
// Print the objects on the current page and their metadata.
console.log(JSON.stringify(res));
// Update the pagination status.
isTruncated = res.data.isTruncated; // Indicates whether there are more objects.
continuationToken = res.data.nextContinuationToken; // The pagination token for the next page.
}
} catch (err) {
// Catch exceptions that occur 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 error code.
} else {
console.log('unknown error: ', err);
}
}
};
// Call the listObjectsV2WithContinuationToken function to list objects page by page.
listObjectsV2WithContinuationToken();
Swift
For more information, see List objects (Swift SDK).
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
do {
// Specify the region where the bucket is located. For example, set the region to cn-hangzhou for China (Hangzhou).
let region = "cn-hangzhou"
// Specify the bucket name.
let bucket = "yourBucketName"
// Optional. Specify the domain name used to access OSS. For example, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
let endpoint: String? = nil
// 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.
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 credentials.
// 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 with paging.
let paginator = client.listObjectsV2Paginator(
ListObjectsV2Request(
bucket: bucket // Specify the name of the bucket whose objects you want to list.
)
)
// Traverse the paginated results to 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 ?? [] {
// Print the object metadata: object name, size in bytes, and last modified time.
print("Object key:\(content.key ?? ""), size: \(String(describing: content.size)), last modified: \(String(describing: content.lastModified))")
}
}
} catch {
// Print the error.
print("error: \(error)")
}
}
}
Ruby
For more information, see List objects (Ruby SDK).
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# Set the endpoint to the one that corresponds to 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.
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 bucket name. Example: examplebucket.
bucket = client.get_bucket('examplebucket')
# List all objects.
objects = bucket.list_objects
objects.each { |o| puts o.key }
Browser.js
For more information, see List objects (Browser.js SDK).
<!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 more information, see List objects (Android SDK).
private String marker = null;
private boolean isCompleted = false;
// List all objects by page.
public void getAllObject() {
do {
OSSAsyncTask task = getObjectList();
// Block the thread to get the NextMarker. To fetch the next page, set the marker to the NextMarker value from the previous response. No marker is needed for the first page.
// This example blocks the thread in a loop to get the NextMarker for pagination. In a production environment, decide whether to block the thread based on your application's requirements.
task.waitUntilFinished();
} while (!isCompleted);
}
// List one page of objects.
public OSSAsyncTask getObjectList() {
// Specify the bucket name.
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
// Specify the maximum number of objects to return per page. If this parameter is not set, the default value is 100. The value of maxKeys cannot be greater than 1,000.
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());
}
// Last page of results.
if (!result.isTruncated()) {
isCompleted = true;
return;
}
// The marker for the next page of results.
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 more information, see List objects (C++ SDK).
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* 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. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize 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() <<
",last modified time:" << object.LastModified() << std::endl;
}
}
nextMarker = outcome.result().NextMarker();
isTruncated = outcome.result().IsTruncated();
} while (isTruncated);
/* Release network resources. */
ShutdownSdk();
return 0;
}
iOS
For more information, see List objects (iOS SDK).
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 more information, see List objects (C SDK).
#include "oss_api.h"
#include "aos_http_io.h"
/* Replace yourEndpoint with 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. */
const char *endpoint = "yourEndpoint";
/* Replace with your bucket name, for example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Replace yourRegion with the region where the bucket is located. For example, if the bucket is 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);
/* 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 sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
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"));
// Configure the following two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specifies whether a CNAME is used. A value of 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 the program entry to initialize global resources such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* The memory pool for memory management, which is equivalent to apr_pool_t. The implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the new memory pool does not inherit from another memory pool. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter contains global configurations, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory for options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize 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);
/* Use the max_ret parameter to set the number of objects to return. */
/* By default, a maximum of 1,000 objects can be listed. If the number of objects to list exceeds 1,000, only the first 1,000 objects in alphabetical order are returned. The truncated value in the response is true, and the next_marker value is returned as the starting point for the next read operation. */
params->max_ret = 100;
aos_str_set(¶ms->prefix, prefix);
aos_str_set(¶ms->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, ¶ms->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(¶ms->marker, nextMarker);
aos_list_init(¶ms->object_list);
aos_list_init(¶ms->common_prefix_list);
} while (params->truncated == AOS_TRUE);
printf("Total %d\n", size);
/* Release the memory pool. This releases the memory allocated to various resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
ossutil
The following example shows how to list all Object information in the bucket examplebucket.
ossutil api list-objects-v2 --bucket examplebucket
For more information, see list-objects-v2 (get-bucket-v2).
OSS console
Log on to the OSS console.
-
In the left-side navigation pane, click Buckets.
-
Click the name of the target bucket. On the bucket details page, click Object Management > Objects.
This page lists all objects in the bucket, displaying 50 objects per page by default. You can increase the number of objects displayed per page to a maximum of 500.
List all objects in a directory
To get a flat list of all objects within a directory and its subdirectories, set the prefix parameter.
The prefix parameter filters by prefix, returning all objects whose name (Key) starts with the specified string. Because OSS uses a flat storage structure with no physical directories, this filter is all you need to retrieve all objects in a logical directory.
Use SDKs
Java
For complete sample code, see List objects (Java SDK V1).
// ...
// Set the prefix.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setPrefix("images/"); // Specify the prefix.
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
// ...
Python
For complete sample code, see List objects (Python SDK V2).
# ...
# Add the prefix parameter.
for page in paginator.iter_page(oss.ListObjectsV2Request(
bucket='your-bucket',
prefix='images/' # Specify the prefix.
)):
# ...
Go
For complete sample code, see List objects (Go SDK V2).
// ...
// Set the prefix.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Prefix: oss.Ptr("images/"), // List all objects with the specified prefix.
}
// ...
Node.js
For complete sample code, see List objects (Node.js).
// ...
// Set the prefix.
const result = await client.listV2({
prefix: 'images/' // Specify the prefix.
});
// ...
Harmony
For complete sample code, see List objects (Harmony SDK).
// ...
// Set the prefix.
const res = await client.listObjectsV2({
bucket: 'yourBucketName',
prefix: 'images/', // Specify the prefix.
});
// ...
Ruby
For complete sample code, see List objects (Ruby SDK).
# ...
# Set the prefix.
objects = bucket.list_objects(:prefix => 'images/') # Specify the prefix.
# ...
Android
For complete sample code, see List objects (Android SDK).
// ...
// Set the prefix.
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
request.setPrefix("images/"); // Specify the prefix.
// ...
C++
For complete sample code, see List objects (C++ SDK).
// ...
// Set the prefix.
ListObjectsRequest request(BucketName);
request.setPrefix("images/"); // Specify the prefix.
// ...
iOS
For complete sample code, see List objects (iOS SDK).
// ...
// Set the prefix.
getBucket.prefix = @"images/"; // Specify the prefix.
// ...
C
For complete sample code, see List objects (C SDK).
// ...
// Set the prefix.
char *prefix = "images/"; // Specify the prefix.
aos_str_set(¶ms->prefix, prefix);
// ...
Use ossutil
The following example shows how to list all Objects in the examplebucket bucket that have the specified prefix dir.
ossutil api list-objects-v2 --bucket examplebucket --prefix dir/
For more usage details, see list-objects-v2 (get-bucket-v2).
Sample output
Assume that 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 request returns the following response:
images/
images/archive/
images/archive/old.zip
images/cat.jpg
images/dog.png
List immediate objects and subdirectories
In addition to the prefix parameter, add the delimiter parameter (typically set to /). This divides the results into two groups: objects and commonPrefixes (subdirectories).
The delimiter parameter is used to group by hierarchy. When set, OSS performs a secondary grouping on the results already filtered by prefix:
-
If an object key does not contain the
/delimiter after theprefix, it is an object. -
If a filename contains a
/after theprefix, the segment up to the first/is treated as a subdirectory.
Use SDKs
Java
For complete sample code, see List objects (Java SDK V1).
// ...
// Set the delimiter.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setPrefix("images/"); // Specify the directory.
listObjectsV2Request.setDelimiter("/"); // Set the delimiter.
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
// Iterate through the objects in the current directory.
for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
System.out.println("Object: " + objectSummary.getKey());
}
// Iterate through the subdirectories.
for (String commonPrefix : result.getCommonPrefixes()) {
System.out.println("Subdirectory: " + commonPrefix);
}
// ...
Python
For complete sample code, see List objects (Python SDK V2).
# ...
# Add the delimiter parameter.
for page in paginator.iter_page(oss.ListObjectsV2Request(
bucket=args.bucket,
prefix="images/", # Specify the directory.
delimiter="/", # Set the delimiter.
)):
# Iterate through the objects in the current directory.
for file in page.contents:
print(f'Object: {file.key}')
# Iterate through the subdirectories.
for prefix in page.common_prefixes:
print(f'Subdirectory: {prefix.prefix}')
# ...
Go
// ...
// Set the delimiter.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Prefix: oss.Ptr("images/"), // Specify the directory.
Delimiter: oss.Ptr("/"), // Set the delimiter.
}
// Iterate through the objects in the current directory.
for _, obj := range lsRes.Contents {
log.Printf("Object: %v\n", oss.ToString(obj.Key))
}
// Iterate through the subdirectories.
for _, prefix := range lsRes.CommonPrefixes {
log.Printf("Subdirectory: %v\n", *prefix.Prefix)
}
// ...
PHP
For complete sample code, see List objects (PHP SDK V2).
// ...
// 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: "/"
));
// Iterate through the paginated results.
foreach ($iter as $page) {
// Iterate through contents to get the objects in the current directory.
foreach ($page->contents ?? [] as $object) {
echo "Object: " . $object->key . PHP_EOL;
}
// Iterate through commonPrefixes to get the subdirectories.
foreach ($page->commonPrefixes ?? [] as $prefixObject) {
echo "Subdirectory: " . $prefixObject->prefix . PHP_EOL;
}
}
// ...
Node.js
For complete sample code, see List objects (Node.js).
// ...
// Set the delimiter.
const result = await client.listV2({
prefix: dir, // Specify the directory.
delimiter: '/' // Set the delimiter.
});
// Iterate through the objects in the current directory.
if (result && result.objects) {
result.objects.forEach(obj => {
console.log('Object: %s', obj.name);
});
}
// Iterate through the subdirectories.
if (result && result.prefixes) {
result.prefixes.forEach(subDir => {
console.log('Subdirectory: %s', subDir);
});
}
// ...
Harmony
For complete sample code, see List objects (Harmony SDK).
// ...
// Set the delimiter.
const res = await client.listObjectsV2({
bucket: 'yourBucketName', // Bucket name.
prefix: 'images/', // Specify the directory.
delimiter: '/', // Set the delimiter.
});
// Iterate through the objects in the current directory.
if (res && res.objects) {
res.objects.forEach(obj => {
console.log('Object:', obj.name);
});
}
// Iterate through the subdirectories.
if (res && res.prefixes) {
res.prefixes.forEach(subDir => {
console.log('Subdirectory:', subDir);
});
}
// ...
Browser.js
For complete sample code, see List objects (Browser.js SDK).
// ...
// Set the delimiter.
let result = await client.list({
prefix: 'images/', // Specify the directory.
delimiter: "/", // Set the delimiter.
});
// Iterate through the objects in the current directory.
result.objects.forEach(function (obj) {
console.log("Object: %s", obj.name);
});
// Iterate through the subdirectories.
result.prefixes.forEach(function (subDir) {
console.log("Subdirectory: %s", subDir);
});
// ...
Ruby
For complete sample code, see List objects (Ruby SDK).
// ...
// Set the delimiter.
objects = bucket.list_objects(prefix: 'images/', delimiter: '/')
// Iterate through the objects in the current directory.
if obj.is_a?(Aliyun::OSS::Object)
puts "Object: #{obj.key}"
end
// Iterate through the subdirectories.
if obj.is_a?(String) # Common Prefix
puts "Subdirectory: #{obj}"
end
// ...
C++
For complete sample code, see List objects (C++ SDK).
// ...
// Set the delimiter.
ListObjectsRequest request(BucketName);
request.setPrefix("images/"); // Specify the directory.
request.setDelimiter("/"); // Set the delimiter.
// Iterate through the objects in the current directory.
for (const auto& object : outcome.result().ObjectSummarys()) {
std::cout << "Object:" << object.Key() << std::endl;
}
// Iterate through the subdirectories.
for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
std::cout << "Subdirectory:" << commonPrefix << std::endl;
}
// ...
C
For complete sample code, see List objects (C SDK).
// ...
// Set the delimiter.
params = oss_create_list_object_params(pool);
aos_str_set(¶ms->prefix, "images/"); // Specify the directory.
aos_str_set(¶ms->delimiter, "/"); // Set the delimiter.
// Iterate through the objects in the current directory.
aos_list_for_each_entry(oss_list_object_content_t, content, ¶ms->object_list, node) {
printf("Object: %.*s\n", content->key.len, content->key.data);
}
// Iterate through the subdirectories.
aos_list_for_each_entry(oss_list_object_common_prefix_t, commonPrefix, ¶ms->common_prefix_list, node) {
printf("Subdirectory: %.*s\n", commonPrefix->prefix.len, commonPrefix->prefix.data);
}
// ...
Use ossutil
The following example shows how to list the Objects in the current directory of the examplebucket bucket.
ossutil api list-objects-v2 --bucket examplebucket --prefix images/ --delimiter /
For more usage details, see list-objects-v2 (get-bucket-v2).
Sample output
Setting both prefix="images/" and delimiter="/" in your request groups the results as follows:
Objects:
images/
images/cat.jpg
images/dog.png
Subdirectories:
images/archive/
List objects after a specified position
Use the startAfter parameter (or marker in some older SDKs) to skip objects that lexicographically precede a specified key.
Use SDKs
Java
For the complete sample code, see List objects (Java SDK V1).
// ...
// 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", // Start listing after the specified object.
));
// ...
Ruby
For the complete sample code, see List objects (Ruby SDK).
# ...
# 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 (Android SDK).
// ...
// 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 (C++ SDK).
// ...
// 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 (iOS SDK).
// ...
// 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 (C SDK).
// ...
// Key code: Set the marker (starting position).
char *nextMarker = "images/cat.jpg"; // Start listing after the specified object.
aos_str_set(¶ms->marker, nextMarker);
// ...
Use ossutil
The following example lists objects that appear after test.txt in the examplebucket bucket.
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
Setting start_after="images/cat.jpg" in the request excludes "images/cat.jpg" and any objects that lexicographically precede it:
images/dog.png
readme.txt
Adjust objects per page
The max-keys parameter specifies the number of objects returned in a single request. The default value is 100, and the maximum is 1,000.
SDKs
Java
For the complete sample code, see List objects (Java SDK V1).
// ...
// Key code: Add the maxKeys parameter to set the number of objects per page.
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setMaxKeys(1000); // Up to 1,000 objects per page.
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, // Up to 1,000 objects per page.
)):
# ...
Go
For the complete sample code, see List objects (Go SDK V2).
// ...
// Key code: Add the MaxKeys parameter to set the number of objects per page.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
MaxKeys: 1000, // Up to 1,000 objects per page.
}
// ...
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: 1000, // Up to 1,000 objects per page.
));
// ...
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 // Up to 1,000 objects per page.
});
// ...
Android
For the complete sample code, see List objects (Android SDK).
// ...
// Key code: Add the maxKeys parameter to set the number of objects per page.
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
request.setMaxKeys(1000); // Up to 1,000 objects per page.
// ...
C++
For the complete sample code, see List objects (C++ SDK).
// ...
// Key code: Add the maxKeys parameter to set the number of objects per page.
ListObjectsRequest request(BucketName);
request.setMaxKeys(1000); // Up to 1,000 objects per page.
// ...
iOS
For the complete sample code, see List objects (iOS SDK).
// ...
// Key code: Add the maxKeys parameter to set the number of objects per page.
getBucket.maxKeys = 1000; // Up to 1,000 objects per page.
// ...
C
For the complete sample code, see List objects (C SDK).
// ...
// Key code: Add the max_ret parameter to set the number of objects per page.
params->max_ret = 1000; // Up to 1,000 objects per page.
// ...
ossutil
The following command lists the first 100 objects with the prefix dir/ in the examplebucket bucket.
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 the following objects:
image/
image/archive/
image/archive/old.zip
image/cat.jpg
image/dog.jpg
readme.txt
-
If
max-keysis set to 2, the objects are returned two per page.Object: image/, Size: 0, Last_modified: 2025-09-22 07:09:49+00:00 Object: image/archive/, Size: 0, Last_modified: 2025-09-22 07:11:32+00:00 =================================== Object: image/archive/old.zip, Size: 10199189, Last_modified: 2025-09-22 07:12:06+00:00 Object: image/cat.jpg, Size: 743970, Last_modified: 2025-09-22 07:10:15+00:00 =================================== Object: image/dog.jpg, Size: 743970, Last_modified: 2025-09-22 07:10:30+00:00 Object: readme.txt, Size: 17, Last_modified: 2025-09-22 07:12:38+00:00 =================================== -
If
max-keysis set to 100, all objects are returned in a single page.Object: image/, Size: 0, Last_modified: 2025-09-22 07:09:49+00:00 Object: image/archive/, Size: 0, Last_modified: 2025-09-22 07:11:32+00:00 Object: image/archive/old.zip, Size: 10199189, Last_modified: 2025-09-22 07:12:06+00:00 Object: image/cat.jpg, Size: 743970, Last_modified: 2025-09-22 07:10:15+00:00 Object: image/dog.jpg, Size: 743970, Last_modified: 2025-09-22 07:10:30+00:00 Object: readme.txt, Size: 17, Last_modified: 2025-09-22 07:12:38+00:00
Production considerations
Performance optimization
-
Increase page size: Setting
max-keysto 1,000 significantly reduces API calls on fast networks, but be mindful of memory usage to avoid loading excessive data. -
Process prefixes in parallel: Sequential listing is slow for buckets with hundreds of thousands of objects or more. Improve performance by processing different prefixes (logical directories) in parallel, such as images/, documents/, and logs/.
-
Cache 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:
-
For periodic, large-scale analysis, use the lower-cost Inventory feature to generate a complete object manifest.
-
To respond to object uploads or deletions in real time, use event notification, which is more efficient and cost-effective than listing objects.
-
-
Configure pagination reasonably: A small page size increases API calls, while a large one can increase single-request processing time and memory usage.
Quotas and limitations
-
Maximum items per response:
ListObjectsandListObjectsV2requests return a maximum of 1,000 objects. -
Sorting method: Lexicographical by object key only.
FAQ
List objects by page number
No.
List all objects in a specific directory
Use the list-objects-v2 (get-bucket-v2) command in ossutil to list all objects in a specific directory, including the directory structure and object names.
Sort objects by last modified time
No. To sort objects by last modified time, use data indexing.