By default, when you list objects in a bucket, the objects are returned in lexicographical order. You can list all objects, objects whose names contain a specified prefix, or a specified number of objects in a bucket.
Use the OSS console
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets.
- On the Buckets page, click the name of the bucket that you want to manage. All objects in the bucket are displayed by page. By default, 50 objects are displayed per page.
Use ossbrowser
You can use ossbrowser to perform the same bucket-level operations that you can perform in the OSS console. You can follow the on-screen instructions in ossbrowser to list objects in a bucket. For more information about how to use ossbrowser, see Use ossbrowser.
Use OSS SDKs
The following sample code provides examples on how to use OSS SDKs for common programming languages to list all objects in a bucket by using simple list. For more information about how to use OSS SDKs for other programming languages to list objects that meet specified conditions in different scenarios, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.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";
// We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked. As a result, the security of all resources in your account is compromised. In this example, access credentials are obtained from environment variables. You need to configure environment variables before you run the sample code.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the prefix in the names of the objects that you want to list. Example: exampledir/object.
String keyPrefix = "exampledir/object";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
// List objects. If you do not specify keyPrefix, all objects in the bucket are listed. If you specify keyPrefix, the objects whose names contain the specified prefix are listed.
ObjectListing objectListing = ossClient.listObjects(bucketName, keyPrefix);
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
System.out.println("\t" + s.getKey());
}
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (OSS) is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
// List objects. If you do not specify a prefix, all objects in the root directory are listed. If you specify a prefix, the objects whose names contain the specified prefix are listed.
$prefix = 'dir/';
$options = array(
'prefix' => $prefix,
);
try {
$listObjectInfo = $ossClient->listObjects($bucket, $options);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
// Query the listed objects.
$objectList = $listObjectInfo->getObjectList();
if (!empty($objectList)) {
print("objectList:\n");
foreach ($objectList as $objectInfo) {
print($objectInfo->getKey() . "\n");
}
}
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',
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Set yourbucketname to the name of your bucket.
bucket: 'yourbucketname'
});
async function list () {
// By default, if no parameter is specified, up to 100 objects can be returned.
const result = await client.list();
console.log(result);
}
list();
# -*- coding: utf-8 -*-
import oss2
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# 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.
# Specify the name of the bucket. Example: examplebucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# List all objects in the bucket.
for obj in oss2.ObjectIteratorV2(bucket):
print(obj.key)
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',
// Specify the temporary AccessKey pair obtained from STS. An 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) {
let result = await client.list({ marker : result.nextMarker });
}
// List the objects whose names start with the prefix my-.
let result = await client.list({
prefix: 'my-'
});
console.log(result);
// List all objects whose names start with the prefix my- and come after the marker my-object.
let result = await client.list({
prefix: 'my-',
marker: 'my-object'
});
console.log(result);
} catch (e) {
console.log(e);
}
}
list();
using Aliyun.OSS;
// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the endpoint based on your business requirements.
var endpoint = "yourEndpoint";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access Object Storage Service (OSS) because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
var listObjectsRequest = new ListObjectsRequest(bucketName);
// Provide a simple list of objects in the specified bucket. By default, 100 objects are returned.
var result = client.ListObjects(listObjectsRequest);
Console.WriteLine("List objects succeeded");
foreach (var summary in result.ObjectSummaries)
{
Console.WriteLine("File name:{0}", summary.Key);
}
}
catch (Exception ex)
{
Console.WriteLine("List objects failed. {0}", ex.Message);
}
// Specify the name of the bucket. Example: examplebucket.
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
// Specify the maximum number of objects that you want to return. If you do not specify this parameter, the value of this parameter is 100. The maximum value of MaxKeys that you can specify is 1000.
request.setMaxKeys(20);
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());
}
}
@Override
public void onFailure(ListObjectsRequest request, ClientException clientException, ServiceException serviceException) {
// 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());
}
}
});
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func main() {
// Create an OSSClient instance.
// 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. Specify your actual endpoint.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
if err != nil {
HandleError(err)
}
// Specify the name of the bucket.
bucketName := "yourBucketName"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
continueToken := ""
for {
lsRes, err := bucket.ListObjectsV2(oss.ContinuationToken(continueToken))
if err != nil {
HandleError(err)
}
// Display the listed objects. By default, a maximum of 100 objects are returned at a time.
for _, object := range lsRes.Objects {
fmt.Println(object.Key, object.Type, object.Size, object.ETag, object.LastModified, object.StorageClass)
}
if lsRes.IsTruncated {
continueToken = lsRes.NextContinuationToken
} else {
break
}
}
}
OSSGetBucketRequest * getBucket = [OSSGetBucketRequest new];
// Specify the name of the bucket. Example: examplebucket.
getBucket.bucketName = @"examplebucket";
// Specify the maximum number of objects that you want to return. If you do not specify this parameter, the value of this parameter is 100. The maximum value of MaxKeys that you can specify is 1000.
getBucket.maxKeys = 20;
OSSTask * getBucketTask = [client getBucket:getBucket];
[getBucketTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {
OSSGetBucketResult * result = task.result;
NSLog(@"get bucket success!");
for (NSDictionary * objectInfo in result.contents) {
NSLog(@"list object: %@", objectInfo);
}
} else {
NSLog(@"get bucket failed, error: %@", task.error);
}
return nil;
}];
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the information about the account that is used to access OSS. */
/* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
std::string AccessKeyId = "yourAccessKeyId";
std::string AccessKeySecret = "yourAccessKeySecret";
/* 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 = "https://oss-cn-hangzhou.aliyuncs.com";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
/* List objects. */
ListObjectsRequest request(BucketName);
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;
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;
}
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
#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";
/* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
const char *access_key_id = "yourAccessKeyId";
const char *access_key_secret = "yourAccessKeySecret";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
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);
aos_str_set(&options->config->access_key_id, access_key_id);
aos_str_set(&options->config->access_key_secret, access_key_secret);
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Configure 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 that is 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);
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 operation releases the memory resources that are allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
Use ossutil
You can use ossutil to list objects. For more information, see List objects.
Use RESTful APIs
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code.
You can call the GetBucket (ListObjects) or ListObjectsV2 (GetBucketV2) operation to list objects in a bucket. We recommend that you use GetBucketV2 (ListObjectsV2) when you develop your applications. To provide backward compatibility, Object Storage Service (OSS) continues to support the GetBucket (ListObjects) operation.
FAQ
Does OSS support listing a specified number of pages of objects?
No, OSS does not support listing a specified number of pages of objects.
How do I list all objects in a specified directory?
You can call the GetBucket (ListObjects) or ListObjectsV2 (GetBucketV2) operation to list all object information in a specified directory, including the directory structure and object name. For more information, see List objects by directory.
Can I sort objects based on the last modified time when I list objects?
No, sorting based on the last modified time is not supported. We recommend that you use the data indexing feature to sort objects based on the last modified time. For more information, see Data indexing.