List objects in CloudBox

Updated at:

By default, objects in an OSS on CloudBox bucket are listed in alphabetical order. You can list all objects in the bucket, objects with a specific prefix, or a specific number of objects.

Use an Alibaba Cloud SDK

You can list all objects in an OSS on CloudBox bucket by using the OSS SDK for Java, Python, or Go (Java SDK 3.15.0 or later, Python SDK V2 1.1.1 or later, or Go SDK V2 v1.2.1 or later). For OSS on CloudBox, the Python and Go SDKs are called in the same way as they are in public cloud OSS. For information about how to create a client, see SDK support. The following code examples use the Java, Python, and Go SDKs.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.List;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;

public class Demo {
    public static void main(String[] args) throws Exception {
        // Specify the data endpoint of the OSS on CloudBox bucket.
        String endpoint = "https://cb-f8z7yvzgwfkl9q0h****.cn-heyuan.oss-cloudbox.aliyuncs.com";
        // Obtain access credentials from environment variables. Before running this 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 OSS on CloudBox bucket. For example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the region where the OSS on CloudBox bucket is located.
        String region = "cn-hangzhou";
        // Specify the ID of the CloudBox.
        String cloudBoxId = "cb-f8z7yvzgwfkl9q0h****";
        // Specify a prefix. For example, exampledir/object.
        String keyPrefix = "exampledir/object";

        // Create an OSSClient instance.
        // Call the shutdown method to release resources when you no longer need the OSSClient instance.
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        conf.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(new DefaultCredentialProvider(credentialsProvider.getCredentials()))
                .clientConfiguration(conf)
                .region(region)
                .cloudBoxId(cloudBoxId)
                .build();

        try {
            // List objects. If you do not set keyPrefix, all objects in the OSS on CloudBox bucket are listed. If you set keyPrefix, 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();
            }
        }
    }
}                  
# -*- coding: utf-8 -*-
import alibabacloud_oss_v2 as oss

# Obtain access credentials from environment variables. Before running this code example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

# Use the default configuration of the SDK.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider

# Specify the region in which the CloudBox is located, such as cn-hangzhou.
cfg.region = "cn-hangzhou"

# Specify the CloudBox ID. After you set the CloudBox ID, the SDK automatically switches the signing product to oss-cloudbox.
cfg.cloud_box_id = "cb-f8z7yvzgwfkl9q0h****"

# Specify the data domain in the CloudboxId.Region.oss-cloudbox.aliyuncs.com format.
cfg.endpoint = "cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com"

# Create an OSS client.
client = oss.Client(cfg)

# Specify the name of the bucket, such as examplebucket.
bucket_name = "examplebucket"
# Specify the prefix. If you do not specify the prefix, all objects in the CloudBox bucket are listed. If you specify the prefix, only objects whose names contain the specified prefix are listed.
key_prefix = "exampledir/object"

# Create a paginator for the list objects operation.
paginator = client.list_objects_v2_paginator()

# Iterate through the pages and print the object information.
for page in paginator.iter_page(oss.ListObjectsV2Request(
        bucket=bucket_name,
        prefix=key_prefix,
    )
):
    for o in page.contents:
        print(f'Object: {o.key}, {o.size}, {o.last_modified}')
package main

import (
	"context"
	"log"

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

func main() {
	// Load the default configuration of the SDK and set the access credentials, region, CloudBox ID, and data domain.
	// Obtain access credentials from environment variables. Before running this code example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		// Specify the region in which the CloudBox is located, such as cn-hangzhou.
		WithRegion("cn-hangzhou").
		// Specify the data domain in the CloudboxId.Region.oss-cloudbox.aliyuncs.com format.
		WithEndpoint("cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com").
		// Specify the CloudBox ID. After you set the CloudBox ID, the SDK automatically switches the signing product to oss-cloudbox.
		WithCloudBoxId("cb-f8z7yvzgwfkl9q0h****")

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

	// Specify the name of the bucket, such as examplebucket.
	bucketName := "examplebucket"
	// Specify the prefix. If you do not specify the prefix, all objects in the CloudBox bucket are listed. If you specify the prefix, only objects whose names contain the specified prefix are listed.
	keyPrefix := "exampledir/object"

	request := &oss.ListObjectsV2Request{
		Bucket: oss.Ptr(bucketName),
		Prefix: oss.Ptr(keyPrefix),
	}

	// Create a paginator for the list objects operation.
	p := client.NewListObjectsV2Paginator(request)

	// Iterate through the pages and print the object information.
	log.Println("Objects:")
	for p.HasNext() {
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v", err)
		}
		for _, obj := range page.Contents {
			log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
		}
	}
}

Use the ossutil command line interface

For more information about how to list objects using ossutil, see list-objects (get-bucket).

Use REST APIs

If your application requires a high degree of customization, you can send REST API requests directly. This requires you to manually write code to calculate signatures.

You can call the GetBucket (ListObjects) or ListObjectsV2 (GetBucketV2) API operation to list objects in a bucket. Use the newer GetBucketV2 (ListObjectsV2) operation for application development. To ensure backward compatibility, OSS continues to support GetBucket (ListObjects).