Objects in a bucket are sorted in lexicographical order. Use the ListObjectsV2 API—or its equivalent in each SDK—to retrieve them by page, filter by prefix, simulate directory traversal, or start from a specific position.
Parameters at a glance
| Parameter | Description | Default | Max |
|---|---|---|---|
prefix | Return only objects whose keys start with this string | — | — |
delimiter | Group keys that contain this character after the prefix into CommonPrefixes | — | — |
startAfter / marker | Skip all keys that come before this value in lexicographical order | — | — |
maxKeys | Maximum number of objects per response | 100 | 1,000 |
continuationToken | Token from the previous response; use it to fetch the next page | — | — |
startAfteris the V2 parameter name. Older SDKs that use ListObjects V1 expose the same concept asmarker.
List all objects
All examples below use a paginator or continuation-token loop to handle buckets with more than 1,000 objects.
Use OSS SDKs
Java
For the complete reference, 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 {
// Endpoint for the China (Hangzhou) region. Replace with your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Read credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
EnvironmentVariableCredentialsProvider credentialsProvider =
CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
String bucketName = "examplebucket";
int maxKeys = 200;
String region = "cn-hangzhou";
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;
// Iterate through all pages using the continuation token from each response.
do {
ListObjectsV2Request request = new ListObjectsV2Request(bucketName)
.withMaxKeys(maxKeys);
request.setContinuationToken(nextContinuationToken);
result = ossClient.listObjectsV2(request);
for (OSSObjectSummary s : result.getObjectSummaries()) {
System.out.println("\t" + s.getKey());
}
nextContinuationToken = result.getNextContinuationToken();
} while (result.isTruncated());
} catch (OSSException oe) {
System.out.println("Error Code: " + oe.getErrorCode());
System.out.println("Request ID: " + oe.getRequestId());
} catch (ClientException ce) {
System.out.println("Client error: " + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}Python
For the complete reference, see List objects (Python SDK V2).
import argparse
import alibabacloud_oss_v2 as oss
parser = argparse.ArgumentParser(description="list objects v2 sample")
parser.add_argument('--region', required=True)
parser.add_argument('--bucket', required=True)
parser.add_argument('--endpoint')
def main():
args = parser.parse_args()
# Read credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss.Client(cfg)
# The paginator handles continuation tokens automatically.
paginator = client.list_objects_v2_paginator()
for page in paginator.iter_page(oss.ListObjectsV2Request(bucket=args.bucket)):
for o in page.contents:
print(f'Object: {o.key}, {o.size}, {o.last_modified}')
if __name__ == "__main__":
main()Go
For the complete reference, 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"
)
var (
region string
bucketName string
)
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() {
flag.Parse()
if len(bucketName) == 0 {
log.Fatalf("bucket name is required")
}
if len(region) == 0 {
log.Fatalf("region is required")
}
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := oss.NewClient(cfg)
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
}
// The paginator iterates through all pages automatically.
p := client.NewListObjectsV2Paginator(request)
var i int
log.Println("Objects:")
for p.HasNext() {
i++
page, err := p.NextPage(context.TODO())
if err != nil {
log.Fatalf("failed to get page %v: %v", i, err)
}
for _, obj := range page.Contents {
log.Printf("Object: %v, %v, %v\n",
oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
}
}
}PHP
For the complete reference, see List objects (PHP SDK V2).
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
"endpoint" => ['help' => 'The endpoint for accessing OSS.', 'required' => False],
"bucket" => ['help' => 'The name of the bucket.', 'required' => True],
];
$longopts = array_map(fn($key) => "$key:", array_keys($optsdesc));
$options = getopt("", $longopts);
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
echo "Error: --$key is required. {$value['help']}" . PHP_EOL;
exit(1);
}
}
$region = $options["region"];
$bucket = $options["bucket"];
// Read credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
$client = new Oss\Client($cfg);
$paginator = new Oss\Paginator\ListObjectsV2Paginator(client: $client);
$iter = $paginator->iterPage(new Oss\Models\ListObjectsV2Request(bucket: $bucket));
foreach ($iter as $page) {
foreach ($page->contents ?? [] as $object) {
print("Object: $object->key, $object->type, $object->size\n");
}
}C#
For the complete reference, see List objects (C# SDK V2).
using OSS = AlibabaCloud.OSS.V2;
var region = "cn-hangzhou"; // Required. The region where the bucket is located.
var endpoint = null as string; // Optional. Override the default endpoint.
var bucket = "your-bucket-name"; // Required. The target bucket name.
// Read credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
var cfg = OSS.Configuration.LoadDefault();
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
cfg.Region = region;
if (endpoint != null) {
cfg.Endpoint = endpoint;
}
using var client = new OSS.Client(cfg);
var paginator = client.ListObjectsV2Paginator(new OSS.Models.ListObjectsV2Request()
{
Bucket = bucket
});
Console.WriteLine("Objects:");
await foreach (var page in paginator.IterPageAsync())
{
foreach (var content in page.Contents ?? [])
{
Console.WriteLine($"Object: {content.Key}, {content.Size}, {content.LastModified}");
}
}Node.js
For the complete reference, see List objects (Node.js).
const OSS = require('ali-oss');
const client = new OSS({
region: 'yourregion',
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
bucket: 'yourbucketname',
});
async function list() {
let continuationToken = null;
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 the complete reference, see List objects.
import Client, { RequestError } from '@aliyun/oss';
const client = new Client({
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
region: 'oss-cn-hangzhou',
});
const listObjectsV2WithContinuationToken = async () => {
try {
let continuationToken: string | undefined;
let isTruncated = true;
while (isTruncated) {
const res = await client.listObjectsV2({
bucket: 'yourBucketName',
continuationToken,
});
console.log(JSON.stringify(res));
isTruncated = res.data.isTruncated;
continuationToken = res.data.nextContinuationToken;
}
} catch (err) {
if (err instanceof RequestError) {
console.log('code: ', err.code);
console.log('message: ', err.message);
console.log('requestId: ', err.requestId);
console.log('status: ', err.status);
} else {
console.log('unknown error: ', err);
}
}
};
listObjectsV2WithContinuationToken();Swift
For the complete reference, see List objects.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
do {
let region = "cn-hangzhou"
let bucket = "yourBucketName"
let endpoint: String? = nil
// Read credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
let credentialsProvider = EnvironmentCredentialsProvider()
let config = Configuration.default()
.withRegion(region)
.withCredentialsProvider(credentialsProvider)
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
let client = Client(config)
let paginator = client.listObjectsV2Paginator(
ListObjectsV2Request(bucket: bucket)
)
for try await page in paginator {
for content in page.contents ?? [] {
print("Object key: \(content.key ?? ""), size: \(String(describing: content.size)), last modified: \(String(describing: content.lastModified))")
}
}
} catch {
print("error: \(error)")
}
}
}Ruby
For the complete reference, see List objects.
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET'],
)
bucket = client.get_bucket('examplebucket')
objects = bucket.list_objects
objects.each { |o| puts o.key }Browser.js
For the complete reference, see List objects.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>List objects</title>
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
</head>
<body>
<script>
const client = new OSS({
region: "yourRegion",
authorizationV4: true,
// Use temporary credentials obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
stsToken: 'yourSecurityToken',
bucket: "examplebucket",
});
async function list() {
try {
// By default, up to 1,000 objects are returned per request.
let result = await client.list();
console.log(result);
// If the result is truncated, fetch the next page from the last marker.
if (result.isTruncated) {
result = await client.list({ marker: result.nextMarker });
}
// List objects whose names start with 'ex'.
result = await client.list({ prefix: "ex" });
console.log(result);
// List objects that start with 'ex' and come after 'example' alphabetically.
result = await client.list({ prefix: "ex", marker: "example" });
console.log(result);
} catch (e) {
console.log(e);
}
}
list();
</script>
</body>
</html>Android
For the complete reference, see List objects.
private String marker = null;
private boolean isCompleted = false;
// Iterate through all pages until the last page is reached.
public void getAllObject() {
do {
OSSAsyncTask task = getObjectList();
// Wait for the current page before requesting the next one.
task.waitUntilFinished();
} while (!isCompleted);
}
// Fetch one page of objects.
public OSSAsyncTask getObjectList() {
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
// Default: up to 100 objects per page. Maximum: 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());
}
if (!result.isTruncated()) {
isCompleted = true;
return;
}
marker = result.getNextMarker();
}
@Override
public void onFailure(ListObjectsRequest request,
ClientException clientException,
ServiceException serviceException) {
isCompleted = true;
if (clientException != null) {
clientException.printStackTrace();
}
if (serviceException != null) {
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
return task;
}C++
For the complete reference, see List objects.
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
std::string Endpoint = "yourEndpoint";
std::string Region = "yourRegion";
std::string BucketName = "examplebucket";
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
std::string nextMarker = "";
bool isTruncated = false;
do {
ListObjectsRequest request(BucketName);
request.setMarker(nextMarker);
auto outcome = client.ListObjects(request);
if (!outcome.isSuccess()) {
std::cout << "ListObjects failed"
<< ", code: " << outcome.error().Code()
<< ", message: " << outcome.error().Message()
<< ", requestId: " << outcome.error().RequestId() << std::endl;
ShutdownSdk();
return -1;
}
for (const auto& object : outcome.result().ObjectSummarys()) {
std::cout << "Object"
<< ", name: " << object.Key()
<< ", size: " << object.Size()
<< ", last modified: " << object.LastModified() << std::endl;
}
nextMarker = outcome.result().NextMarker();
isTruncated = outcome.result().IsTruncated();
} while (isTruncated);
ShutdownSdk();
return 0;
}iOS
For the complete reference, see List objects.
do {
OSSGetBucketRequest *getBucket = [OSSGetBucketRequest new];
getBucket.bucketName = @"examplebucket";
getBucket.marker = _marker;
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;
_isCompleted = NO;
} else {
_isCompleted = YES;
}
} else {
_isCompleted = YES;
NSLog(@"Get bucket failed, error: %@", task.error);
}
return nil;
}];
[getBucketTask waitUntilFinished];
} while (!_isCompleted);C
For the complete reference, see List objects.
#include "oss_api.h"
#include "aos_http_io.h"
const char *endpoint = "yourEndpoint";
const char *bucket_name = "examplebucket";
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
aos_str_set(&options->config->endpoint, endpoint);
// Read credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
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"));
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
options->config->is_cname = 0;
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
aos_pool_t *pool;
aos_pool_create(&pool, NULL);
oss_request_options_t *oss_client_options;
oss_client_options = oss_request_options_create(pool);
init_options(oss_client_options);
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);
// By default, a single request returns up to 1,000 objects. Set max_ret to reduce that.
params->max_ret = 100;
aos_str_set(¶ms->prefix, prefix);
aos_str_set(¶ms->marker, nextMarker);
printf("Object\tSize\tLastModified\n");
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);
aos_pool_destroy(pool);
aos_http_io_deinitialize();
return 0;
}Use ossutil
ossutil api list-objects-v2 --bucket examplebucketFor more information, see list-objects-v2 (get-bucket-v2).
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets.
Click the target bucket, then go to Object Management > Objects.
The page displays all objects in paginated form. The default page size is 50, with a maximum of 500.
List objects in a specific directory
OSS uses a flat storage structure—there are no physical folders. A "directory" in OSS is a common key prefix, such as images/. Two listing modes are available depending on how much of the directory tree you need to see.
Flat listing vs. hierarchical listing
| Mode | Parameters | Returns |
|---|---|---|
| Flat | prefix only | All objects under the prefix, including those in subdirectories |
| Hierarchical | prefix + delimiter | Only the direct contents of the prefix: immediate objects and one level of subdirectories |
Flat listing: all objects under a prefix
Set prefix to the directory path you want to traverse. The response includes all keys that start with that prefix, regardless of how many levels deep they are.
Example bucket contents:
images/cat.jpg
images/dog.png
images/archive/old.zip
readme.txtWith prefix="images/", OSS matches every key that starts with images/ and returns:
images/
images/archive/
images/archive/old.zip
images/cat.jpg
images/dog.pngAll objects under images/—including the nested images/archive/old.zip—appear directly in the response.
Use OSS SDKs
Java
For the complete sample code, see List objects (Java SDK).
// ...
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setPrefix("images/");
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
// ...Python
For the complete sample code, see List objects (Python SDK V2).
# ...
for page in paginator.iter_page(oss.ListObjectsV2Request(
bucket='your-bucket',
prefix='images/',
)):
# ...Go
For the complete sample code, see List objects (Go SDK V2).
// ...
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Prefix: oss.Ptr("images/"),
}
// ...Node.js
For the complete sample code, see List objects (Node.js).
// ...
const result = await client.listV2({ prefix: 'images/' });
// ...Harmony
For the complete sample code, see List objects.
// ...
const res = await client.listObjectsV2({
bucket: 'yourBucketName',
prefix: 'images/',
});
// ...Ruby
For the complete sample code, see List objects.
# ...
objects = bucket.list_objects(:prefix => 'images/')
# ...Android
For the complete sample code, see List objects.
// ...
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
request.setPrefix("images/");
// ...C++
For the complete sample code, see List objects.
// ...
ListObjectsRequest request(BucketName);
request.setPrefix("images/");
// ...iOS
For the complete sample code, see List objects.
// ...
getBucket.prefix = @"images/";
// ...C
For the complete sample code, see List objects.
// ...
char *prefix = "images/";
aos_str_set(¶ms->prefix, prefix);
// ...Use ossutil
ossutil api list-objects-v2 --bucket examplebucket --prefix dir/For more information, see list-objects-v2 (get-bucket-v2).
Hierarchical listing: immediate objects and subdirectories
Add delimiter="/" alongside prefix to split the response into two groups:
Objects (
Contents): keys that do not contain/after the prefix—these are the direct files in the current directory.CommonPrefixes: keys that contain
/after the prefix are collapsed. The part from the beginning up to the first/is returned as a single entry—these represent subdirectories.
Using the same example bucket:
With prefix="images/" and delimiter="/", OSS processes the filtered results in a second step: keys without a / after the prefix go into Contents; keys with a / are collapsed into CommonPrefixes. The response is:
Objects:
images/
images/cat.jpg
images/dog.png
Directories:
images/archive/images/archive/old.zip does not appear directly—it is collapsed under images/archive/.
Use OSS SDKs
Java
For the complete sample code, see List objects (Java SDK).
// ...
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setPrefix("images/");
listObjectsV2Request.setDelimiter("/");
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
for (OSSObjectSummary objectSummary : result.getObjectSummaries()) {
System.out.println("Object: " + objectSummary.getKey());
}
for (String commonPrefix : result.getCommonPrefixes()) {
System.out.println("Subdirectory: " + commonPrefix);
}
// ...Python
For the complete sample code, see List objects (Python SDK V2).
# ...
for page in paginator.iter_page(oss.ListObjectsV2Request(
bucket=args.bucket,
prefix="images/",
delimiter="/",
)):
for file in page.contents:
print(f'Object: {file.key}')
for prefix in page.common_prefixes:
print(f'Subdirectory: {prefix.prefix}')
# ...Go
For the complete sample code, see List objects (Go SDK V2).
// ...
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Prefix: oss.Ptr("images/"),
Delimiter: oss.Ptr("/"),
}
// ...
for _, obj := range lsRes.Contents {
log.Printf("Object: %v\n", oss.ToString(obj.Key))
}
for _, prefix := range lsRes.CommonPrefixes {
log.Printf("Subdirectory: %v\n", *prefix.Prefix)
}
// ...PHP
For the complete sample code, see List objects (PHP SDK V2).
// ...
$paginator = new Oss\Paginator\ListObjectsV2Paginator(client: $client);
$iter = $paginator->iterPage(new Oss\Models\ListObjectsV2Request(
bucket: $bucket,
prefix: "",
delimiter: "/"
));
foreach ($iter as $page) {
foreach ($page->contents ?? [] as $object) {
echo "Object: " . $object->key . PHP_EOL;
}
foreach ($page->commonPrefixes ?? [] as $prefixObject) {
echo "Subdirectory: " . $prefixObject->prefix . PHP_EOL;
}
}
// ...Node.js
For the complete sample code, see List objects (Node.js).
// ...
const result = await client.listV2({
prefix: dir,
delimiter: '/',
});
if (result && result.objects) {
result.objects.forEach(obj => console.log('Object: %s', obj.name));
}
if (result && result.prefixes) {
result.prefixes.forEach(subDir => console.log('Subdirectory: %s', subDir));
}
// ...Harmony
For the complete sample code, see List objects.
// ...
const res = await client.listObjectsV2({
bucket: 'yourBucketName',
prefix: 'images/',
delimiter: '/',
});
if (res && res.objects) {
res.objects.forEach(obj => console.log('Object:', obj.name));
}
if (res && res.prefixes) {
res.prefixes.forEach(subDir => console.log('Subdirectory:', subDir));
}
// ...Browser.js
For the complete sample code, see List objects.
// ...
let result = await client.list({
prefix: 'images/',
delimiter: "/",
});
result.objects.forEach(obj => console.log("Object: %s", obj.name));
result.prefixes.forEach(subDir => console.log("Subdirectory: %s", subDir));
// ...Ruby
For the complete sample code, see List objects.
# ...
objects = bucket.list_objects(prefix: 'images/', delimiter: '/')
objects.each do |obj|
if obj.is_a?(Aliyun::OSS::Object)
puts "Object: #{obj.key}"
elsif obj.is_a?(String)
puts "Subdirectory: #{obj}"
end
end
# ...C++
For the complete sample code, see List objects.
// ...
ListObjectsRequest request(BucketName);
request.setPrefix("images/");
request.setDelimiter("/");
// ...
for (const auto& object : outcome.result().ObjectSummarys()) {
std::cout << "Object: " << object.Key() << std::endl;
}
for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
std::cout << "Subdirectory: " << commonPrefix << std::endl;
}
// ...C
For the complete sample code, see List objects.
// ...
aos_str_set(¶ms->prefix, "images/");
aos_str_set(¶ms->delimiter, "/");
// ...
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);
}
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
ossutil api list-objects-v2 --bucket examplebucket --prefix images/ --delimiter /For more information, see list-objects-v2 (get-bucket-v2).
List objects after a specified position
Use startAfter (or marker in older SDKs) to skip all objects that come before a specified key in lexicographical order. This is useful for resuming a listing from a known position or implementing cursor-based pagination.
Example: With start-after="images/cat.jpg", the response skips images/cat.jpg and everything before it:
images/dog.png
readme.txt(images/archive/old.zip comes before images/cat.jpg alphabetically, so it is also excluded.)
Use OSS SDKs
Java
For the complete sample code, see List objects (Java SDK).
// ...
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setStartAfter("images/cat.jpg");
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
// ...Python
For the complete sample code, see List objects (Python SDK V2).
# ...
for page in paginator.iter_page(oss.ListObjectsV2Request(
bucket=args.bucket,
start_after="images/cat.jpg",
)):
# ...Go
For the complete sample code, see List objects (Go SDK V2).
// ...
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
StartAfter: oss.Ptr("images/cat.jpg"),
}
// ...PHP
For the complete sample code, see List objects (PHP SDK V2).
// ...
$iter = $paginator->iterPage(new Oss\Models\ListObjectsV2Request(
bucket: $bucket,
startAfter: "images/cat.jpg",
));
// ...Ruby
For the complete sample code, see List objects.
# ...
objects = bucket.list_objects(:marker => 'images/cat.jpg')
# ...Android
For the complete sample code, see List objects.
// ...
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
request.setMarker("images/cat.jpg");
// ...C++
For the complete sample code, see List objects.
// ...
ListObjectsRequest request(BucketName);
request.setMarker("images/cat.jpg");
// ...iOS
For the complete sample code, see List objects.
// ...
getBucket.marker = @"images/cat.jpg";
// ...C
For the complete sample code, see List objects.
// ...
char *nextMarker = "images/cat.jpg";
aos_str_set(¶ms->marker, nextMarker);
// ...Use ossutil
ossutil api list-objects-v2 --bucket examplebucket --start-after test.txtFor more information, see list-objects-v2 (get-bucket-v2).
Adjust the number of objects per page
The maxKeys parameter sets the maximum number of objects returned per request. The default is 100; the maximum is 1,000. A higher value reduces the number of API calls for large buckets.
Use OSS SDKs
Java
For the complete sample code, see List objects (Java SDK).
// ...
ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
listObjectsV2Request.setMaxKeys(1000);
ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);
// ...Python
For the complete sample code, see List objects (Python SDK V2).
# ...
for page in paginator.iter_page(oss.ListObjectsV2Request(
bucket=args.bucket,
max_keys=1000,
)):
# ...Go
For the complete sample code, see List objects (Go SDK V2).
// ...
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
MaxKeys: 1000,
}
// ...PHP
For the complete sample code, see List objects (PHP SDK V2).
// ...
$iter = $paginator->iterPage(new Oss\Models\ListObjectsV2Request(
bucket: $bucket,
maxKeys: 10,
));
// ...Node.js
For the complete sample code, see List objects (Node.js).
// ...
const result = await client.listV2({ "max-keys": 1000 });
// ...Android
For the complete sample code, see List objects.
// ...
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
request.setMaxKeys(1000);
// ...C++
For the complete sample code, see List objects.
// ...
ListObjectsRequest request(BucketName);
request.setMaxKeys(1000);
// ...iOS
For the complete sample code, see List objects.
// ...
getBucket.maxKeys = 1000;
// ...C
For the complete sample code, see List objects.
// ...
params->max_ret = 1000;
// ...Use ossutil
ossutil api list-objects-v2 --bucket examplebucket --prefix dir/ --max-keys 100For more information, see list-objects-v2 (get-bucket-v2).
Effect of page size on pagination:
maxKeys=2: all objects returned in pages of 2.
maxKeys=100: all objects returned in pages of 100.
Apply in production
Performance optimization
Maximize page size: Set
max-keysto 1,000 to minimize the number of API calls, especially on fast networks. Monitor memory usage when processing each page.Process prefixes in parallel: For buckets with hundreds of thousands of objects, sequential listing is slow. Divide the bucket by logical directory (e.g.,
images/,documents/,logs/) and process each prefix concurrently.Cache stable directory structures: If the top-level directory layout rarely changes, cache listing results to avoid redundant API calls.
Cost control
Avoid periodic full scans: Repeatedly listing all objects in a large bucket generates many API calls. Consider these alternatives:
Inventory: generates a complete object manifest on a schedule at lower cost. Best for periodic, large-scale analysis.
Event notifications: trigger actions in real time when objects are uploaded or deleted. More efficient than polling with list operations.
Right-size your page size: A page size that is too small multiplies API calls; one that is too large increases memory consumption and response time per request. Tune
maxKeysbased on your processing capacity.
Limitations
A single
ListObjectsorListObjectsV2request returns at most 1,000 object keys.Objects are sorted only by key in lexicographical order. Sorting by last modified time or other attributes is not supported.
Listing a specific number of pages is not supported.
FAQ
Does OSS support listing a specified number of pages of objects?
No. The API does not support page-number-based access. Use continuation tokens (continuationToken / nextContinuationToken) to iterate through pages sequentially.
How do I list all objects in a specific directory?
Set the prefix parameter to the directory path (e.g., images/). To list everything recursively—including nested subdirectories—omit delimiter. To list only the immediate contents, add delimiter="/".
For a command-line option, use list-objects-v2 (get-bucket-v2) in ossutil 2.0.
Is sorting by last modified time supported when listing objects?
No. To find objects by last modified time, use data indexing to query by time range.