All Products
Search
Document Center

Object Storage Service:List objects

Last Updated:Dec 13, 2024

By default, when you list objects in an Object Storage Service (OSS) 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.

Procedure

Use the OSS console

  1. Log on to the OSS console.

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

  3. On the Buckets page, find the desired bucket.

    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 based on your requirements, 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";
        // 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 prefix in the names of the objects that you want to list. Example: exampledir/object. 
        String keyPrefix = "exampledir/object";
        // 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. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

try {
    // 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. 
    $provider = new EnvironmentVariableCredentialsProvider();
    // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
    $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // Specify the name of the bucket. Example: examplebucket. 
    $bucket= "examplebucket";
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint, 
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"       
    );
    $ossClient = new OssClient($config);
    $listObjectInfo = $ossClient->listObjects($bucket);
    printf("Bucket Name: %s". "\n",$listObjectInfo->getBucketName());
    printf("Prefix: %s". "\n",$listObjectInfo->getPrefix());
    printf("Marker: %s". "\n",$listObjectInfo->getMarker());
    printf("Next Marker: %s". "\n",$listObjectInfo->getNextMarker());
    printf("Max Keys: %s". "\n",$listObjectInfo->getMaxKeys());
    printf("Delimiter: %s". "\n",$listObjectInfo->getDelimiter());
    printf("Is Truncated: %s". "\n",$listObjectInfo->getIsTruncated());
    $objectList = $listObjectInfo->getObjectList();
    $prefixList = $listObjectInfo->getPrefixList();
    if (!empty($objectList)) {
        print("objectList:\n");
        foreach ($objectList as $objectInfo) {
            printf("Object Name: %s". "\n",$objectInfo->getKey());
            printf("Object Size: %s". "\n",$objectInfo->getSize());
            printf("Object Type: %s". "\n",$objectInfo->getType());
            printf("Object ETag: %s". "\n",$objectInfo->getETag());
            printf("Object Last Modified: %s". "\n",$objectInfo->getLastModified());
            printf("Object Storage Class: %s". "\n",$objectInfo->getStorageClass());

            if ($objectInfo->getRestoreInfo()){
                printf("Restore Info: %s". "\n",$objectInfo->getRestoreInfo() );
            }

            if($objectInfo->getOwner()){
                printf("Owner Id:".$objectInfo->getOwner()->getId() . "\n");
                printf("Owner Name:".$objectInfo->getOwner()->getDisplayName() . "\n");
            }
        }
    }
    if (!empty($prefixList)) {
        print("prefixList: \n");
        foreach ($prefixList as $prefixInfo) {
            printf("Common Prefix:%s\n",$prefixInfo->getPrefix());
        }
    }
} catch (OssException $e) {
    printf($e->getMessage() . "\n");
    return;
}
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 () {
    // 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
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# List all objects in the bucket. 
for obj in oss2.ObjectIteratorV2(bucket):
    print(obj.key)
<!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>
          
using Aliyun.OSS;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
var endpoint = "yourEndpoint";
// 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. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
c.SetRegion(region);
try
{
    var listObjectsRequest = new ListObjectsRequest(bucketName);
    // List objects in the bucket by using simple list. 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 to return. If you do not specify this parameter, up to 100 objects are returned. The maximum value that you can specify for MaxKeys is 1000. 
request.setMaxKeys(20);

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 (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// 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. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// 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. 
	// Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.  
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "yourBucketName" // Replace yourBucketName with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Specify the position from which the list starts.
	continueToken := ""

	for {
		// List all objects.
		lsRes, err := bucket.ListObjectsV2(oss.ContinuationToken(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Display the listed objects. By default, up to 100 objects are returned at a time. 
		for _, object := range lsRes.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
		}

		// If you want to list more objects, update the value of the continueToken parameter. 
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}
OSSGetBucketRequest * getBucket = [OSSGetBucketRequest new];
// Specify the name of the bucket. Example: examplebucket. 
getBucket.bucketName = @"examplebucket";
// Specify the maximum number of returned objects. By default, the value of this parameter is 100. The maximum value 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;
}];
// Implement synchronous blocking to wait for the task to complete. 
// [getBucketTask waitUntilFinished];
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

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

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

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

Use ossutil

The following example demonstrates how to list all objects in examplebucket. For more information about the request, see list-objects (get-bucket).

ossutil api list-objects --bucket examplebucket

Use the OSS API

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 call GetBucketV2 (ListObjectsV2) when you develop your applications. To provide backward compatibility, OSS continues its support for 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 GetBucket (ListObjects) or ListObjectsV2 (GetBucketV2) to list information about all objects in a directory, including the directory structure and object names. For more information, see List objects by directory.

Can I sort objects based on the last modified time when I list objects?

No, you cannot sort objects based on the last modified time when you list objects. If you need to sort objects based on the last modified time, we recommend that you use the data indexing feature. For more information, see Data indexing.