Cette opération répertorie tous les objets d'un bucket.
SDK
Java
Pour plus d'informations, consultez la rubrique 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
Pour plus d'informations, consultez la rubrique 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
Pour plus d'informations, consultez la rubrique 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
Pour plus d'informations, consultez la rubrique 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.
// Load access credentials from environment variables.
// EnvironmentVariableCredentialsProvider reads the AccessKey ID and AccessKey secret
// from environment variables, keeping credentials out of your source code.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default SDK configuration.
$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 OSS client.
$client = new Oss\Client($cfg);
// Use ListObjectsV2Paginator to list all objects across pages.
// The outer foreach iterates over pages; the inner foreach iterates over objects on each page.
$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 the name, type, and size of each object.
print("Object: $object->key, $object->type, $object->size\n");
// Example output: Object: example/photo.jpg, Normal, 10240
}
}
C#
Pour plus d'informations, consultez la rubrique List objects (C# SDK V2).
using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou.
var endpoint = null as string; // Optional. Specify the domain name used to access the OSS service. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var bucket = "your bucket name"; // Required. The name of the destination bucket.
// Load the default configurations of the OSS SDK. The configurations automatically read credential information (such as AccessKey) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set the use of environment variables to obtain credentials for identity verification (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET).
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket in the configuration.
cfg.Region = region;
// If an endpoint is specified, it overwrites 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 destination bucket.
var paginator = client.ListObjectsV2Paginator(new OSS.Models.ListObjectsV2Request()
{
Bucket = bucket
});
// Print the information of all objects in the bucket.
Console.WriteLine("Objects:");
await foreach (var page in paginator.IterPageAsync()) // Asynchronously traverse each page of results.
{
// Traverse each object on the current page.
foreach (var content in page.Contents ?? [])
{
// Print the object information: key, size (in bytes), and last modified time.
Console.WriteLine($"Object:{content.Key}, {content.Size}, {content.LastModified}");
}
}
Node.js
Pour plus d'informations, consultez la rubrique 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 running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
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
Pour plus d'informations, consultez la rubrique 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
Pour plus d'informations, consultez la rubrique 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
Pour plus d'informations, consultez la rubrique 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
Pour plus d'informations, consultez la rubrique 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({
// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: "yourRegion",
authorizationV4: true,
// The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token (SecurityToken) obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
});
async function list(dir) {
try {
// By default, a maximum of 1,000 files are returned.
let result = await client.list();
console.log(result);
// Continue to obtain the file list starting from the file that follows the last file read in the previous list operation.
if (result.isTruncated) {
result = await client.list({ marker: result.nextMarker });
}
// List files that have the prefix 'ex'.
result = await client.list({
prefix: "ex",
});
console.log(result);
// List files that have the prefix 'ex' and whose names come after 'example' in alphabetical order.
result = await client.list({
prefix: "ex",
marker: "example",
});
console.log(result);
} catch (e) {
console.log(e);
}
}
list();
</script>
</body>
</html>
Android
Pour plus d'informations, consultez la rubrique 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++
Pour plus d'informations, consultez la rubrique 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
Pour plus d'informations, consultez la rubrique 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
Pour plus d'informations, consultez la rubrique 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
L'exemple suivant montre comment répertorier toutes les informations relatives aux Object du bucket examplebucket.
ossutil api list-objects-v2 --bucket examplebucket
Pour plus d'informations, consultez la rubrique list-objects-v2 (get-bucket-v2).
OSS console
Connectez-vous à la console OSS.
Dans le volet de navigation de gauche, cliquez sur Buckets.
-
Cliquez sur le nom du bucket cible. Sur la page des détails du bucket, cliquez sur Object Management > Objects.
Cette page répertorie tous les objets du bucket et affiche 50 objets par page par défaut. Vous pouvez augmenter le nombre d'objets affichés par page jusqu'à un maximum de 500.
La console OSS n'affiche pas le nombre total d'objets dans le bucket et la navigation par pagination n'indique pas le nombre total de pages. Pour obtenir un décompte exact des objets, utilisez l'une des méthodes suivantes :
Exécutez la commande
ossutil ls oss://examplebucketpour répertorier tous les objets. La sortie inclut le nombre total d'objets (par exemple,Object Number is: 22).Utilisez la fonctionnalité data indexing de la console OSS pour interroger et compter les objets selon des conditions spécifiques.
Les objets d'un bucket sont triés par ordre lexicographique par défaut. Vous pouvez répertorier tous les objets, les objets par répertoire ou ajuster le nombre d'objets renvoyés par page.
Répertorier tous les objets d'un répertoire
Pour obtenir une liste plate de tous les objets contenus dans un répertoire et ses sous-répertoires, définissez le paramètre prefix.
Le paramètre prefix filtre par préfixe et renvoie tous les objets dont le nom (Key) commence par la chaîne spécifiée. Étant donné qu'OSS utilise une structure de stockage plate sans répertoires physiques, ce filtre suffit pour récupérer tous les objets d'un répertoire logique.
Utiliser les SDK
Java
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique List objects (Node.js).
// ...
// Set the prefix.
const result = await client.listV2({
prefix: 'images/' // Specify the prefix.
});
// ...
Harmony
Pour obtenir l'exemple de code complet, consultez la rubrique List objects (Harmony SDK).
// ...
// Set the prefix.
const res = await client.listObjectsV2({
bucket: 'yourBucketName',
prefix: 'images/', // Specify the prefix.
});
// ...
Ruby
Pour obtenir l'exemple de code complet, consultez la rubrique List objects (Ruby SDK).
# ...
# Set the prefix.
objects = bucket.list_objects(:prefix => 'images/') # Specify the prefix.
# ...
Android
Pour obtenir l'exemple de code complet, consultez la rubrique List objects (Android SDK).
// ...
// Set the prefix.
ListObjectsRequest request = new ListObjectsRequest("examplebucket");
request.setPrefix("images/"); // Specify the prefix.
// ...
C++
Pour obtenir l'exemple de code complet, consultez la rubrique List objects (C++ SDK).
// ...
// Set the prefix.
ListObjectsRequest request(BucketName);
request.setPrefix("images/"); // Specify the prefix.
// ...
iOS
Pour obtenir l'exemple de code complet, consultez la rubrique List objects (iOS SDK).
// ...
// Set the prefix.
getBucket.prefix = @"images/"; // Specify the prefix.
// ...
C
Pour obtenir l'exemple de code complet, consultez la rubrique List objects (C SDK).
// ...
// Set the prefix.
char *prefix = "images/"; // Specify the prefix.
aos_str_set(¶ms->prefix, prefix);
// ...
Utiliser ossutil
L'exemple suivant montre comment répertorier tous les Object du bucket examplebucket qui possèdent le préfixe spécifié dir.
ossutil api list-objects-v2 --bucket examplebucket --prefix dir/
Pour plus de détails sur l'utilisation, consultez la rubrique list-objects-v2 (get-bucket-v2).
Exemple de sortie
Supposons que le bucket contienne les objets suivants :
images/cat.jpg
images/dog.png
images/archive/old.zip
readme.txt
Lorsque vous définissez prefix="images/" dans votre requête, celle-ci renvoie la réponse suivante :
images/
images/archive/
images/archive/old.zip
images/cat.jpg
images/dog.png
Répertorier les objets immédiats et les sous-répertoires
En plus du paramètre prefix, ajoutez le paramètre delimiter (généralement défini sur /). Cette opération divise les résultats en deux groupes : les objects et les commonPrefixes (sous-répertoires).
Le paramètre delimiter sert à regrouper par hiérarchie. Lorsqu'il est défini, OSS effectue un regroupement secondaire sur les résultats déjà filtrés par le paramètre prefix :
Si une clé d'objet ne contient pas le délimiteur
/après leprefix, il s'agit d'un objet.Si un nom de fichier contient un
/après leprefix, le segment jusqu'au premier/est traité comme un sous-répertoire.
Utiliser les SDK
Java
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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++
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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);
}
// ...
Utiliser ossutil
L'exemple suivant montre comment répertorier les Object du répertoire actuel du bucket examplebucket.
ossutil api list-objects-v2 --bucket examplebucket --prefix images/ --delimiter /
Pour plus de détails sur l'utilisation, consultez la rubrique list-objects-v2 (get-bucket-v2).
Exemple de sortie
La définition simultanée des paramètres prefix="images/" et delimiter="/" dans votre requête regroupe les résultats comme suit :
Objects:
images/
images/cat.jpg
images/dog.png
Subdirectories:
images/archive/
Répertorier les objets à partir d'une position spécifiée
Utilisez le paramètre startAfter (ou marker dans certains SDK plus anciens) pour ignorer les objets qui précèdent lexicographiquement une clé spécifiée.
Utiliser les SDK
Java
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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++
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique List objects (iOS SDK).
// ...
// Key code: Set the marker (starting position).
getBucket.marker = @"images/cat.jpg"; // Start listing after the specified object.
// ...
C
Pour obtenir l'exemple de code complet, consultez la rubrique 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);
// ...
Utiliser ossutil
L'exemple suivant répertorie les objects qui apparaissent après test.txt dans le bucket examplebucket.
ossutil api list-objects-v2 --bucket examplebucket --start-after test.txt
Pour plus d'informations, consultez la rubrique list-objects-v2 (get-bucket-v2).
Exemple de sortie :
Supposons que le bucket contienne les éléments suivants :
images/cat.jpg
images/dog.png
images/archive/old.zip
readme.txt
La définition du paramètre start_after="images/cat.jpg" dans la requête exclut "images/cat.jpg" ainsi que tous les objets qui le précèdent lexicographiquement :
images/dog.png
readme.txt
Ajuster le nombre d'objets par page
Le paramètre max-keys spécifie le nombre d'objets renvoyés dans une seule requête. La valeur par défaut est 100 et le maximum est 1 000.
SDK
Java
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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++
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
Pour obtenir l'exemple de code complet, consultez la rubrique 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
La commande suivante répertorie les 100 premiers objects avec le préfixe dir/ dans le bucket examplebucket.
ossutil api list-objects-v2 --bucket examplebucket --prefix dir/ --max-keys 100
Pour plus d'informations, consultez la rubrique list-objects-v2 (get-bucket-v2).
Exemple de sortie :
Supposons que le bucket contienne les objets suivants :
image/
image/archive/
image/archive/old.zip
image/cat.jpg
image/dog.jpg
readme.txt
-
Si le paramètre
max-keysest défini sur 2, les objets sont renvoyés deux par 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 =================================== -
Si le paramètre
max-keysest défini sur 100, tous les objets sont renvoyés sur une seule 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
Considérations pour la production
Optimisation des performances
Augmenter la taille des pages : Définir le paramètre
max-keyssur 1 000 réduit considérablement le nombre d'appels API sur les réseaux rapides, mais soyez attentif à l'utilisation de la mémoire afin d'éviter de charger des données excessives.Traiter les préfixes en parallèle : Le listage séquentiel est lent pour les buckets contenant des centaines de milliers d'objets ou plus. Améliorez les performances en traitant différents préfixes (répertoires logiques) en parallèle, tels que images/, documents/ et logs/.
Mettre en cache la structure des répertoires : Pour les structures de répertoires qui changent rarement, mettez en cache les résultats du listage afin de réduire les appels API redondants.
Contrôle des coûts
-
Éviter les analyses complètes fréquentes : Répertorier périodiquement tous les objets d'un grand bucket peut être coûteux. Envisagez ces alternatives plus économiques :
Pour les analyses volumineuses périodiques, utilisez la fonctionnalité Inventory moins coûteuse pour générer un manifeste complet des objets.
Pour répondre en temps réel aux téléchargements ou suppressions d'objets, utilisez les event notification, qui sont plus efficaces et économiques que le listage des objets.
Configurer raisonnablement la pagination : Une petite taille de page augmente le nombre d'appels API, tandis qu'une taille importante peut accroître le temps de traitement d'une seule requête et l'utilisation de la mémoire.
Quotas et limites
Nombre maximal d'éléments par réponse : Les requêtes
ListObjectsetListObjectsV2renvoient un maximum de 1 000 objets.Méthode de tri : Ordre lexicographique uniquement par clé d'objet.
FAQ
Répertorier les objets par numéro de page
Non.
Répertorier tous les objets d'un répertoire spécifique
Utilisez la commande list-objects-v2 (get-bucket-v2) dans ossutil pour répertorier tous les objets d'un répertoire spécifique, y compris la structure des répertoires et les noms des objets.
Trier les objets par date de dernière modification
Non. Pour trier les objets par date de dernière modification, utilisez la fonctionnalité data indexing.