///<summary>/// Shows how to list the objects in an Amazon S3 bucket.///</summary>///<param name="client">An initialized Amazon S3 client object.</param>///<param name="bucketName">The name of the bucket for which to list/// the contents.</param>///<returns>A boolean value indicating the success or failure of the/// copy operation.</returns>publicstaticasync Task<bool> ListBucketContentsAsync(IAmazonS3 client, string bucketName){try{var request = new ListObjectsV2Request
{
BucketName = bucketName,
MaxKeys = 5,
};
Console.WriteLine("--------------------------------------");
Console.WriteLine($"Listing the contents of {bucketName}:");
Console.WriteLine("--------------------------------------");
ListObjectsV2Response response;
do{
response = await client.ListObjectsV2Async(request);
response.S3Objects
.ForEach(obj => Console.WriteLine($"{obj.Key,-35}{obj.LastModified.ToShortDateString(),10}{obj.Size,10}"));
// If the response is truncated, set the request ContinuationToken// from the NextContinuationToken property of the response.
request.ContinuationToken = response.NextContinuationToken;
}
while (response.IsTruncated);
returntrue;
}
catch (AmazonS3Exception ex)
{
Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' getting list of objects.");
returnfalse;
}
}
使用分頁程式列出物件。
using System;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;
///<summary>/// The following example lists objects in an Amazon Simple Storage/// Service (Amazon S3) bucket.///</summary>publicclassListObjectsPaginator{privateconststring BucketName = "amzn-s3-demo-bucket";
publicstaticasync Task Main(){
IAmazonS3 s3Client = new AmazonS3Client();
Console.WriteLine($"Listing the objects contained in {BucketName}:\n");
await ListingObjectsAsync(s3Client, BucketName);
}
///<summary>/// This method uses a paginator to retrieve the list of objects in an/// an Amazon S3 bucket.///</summary>///<param name="client">An Amazon S3 client object.</param>///<param name="bucketName">The name of the S3 bucket whose objects/// you want to list.</param>publicstaticasync Task ListingObjectsAsync(IAmazonS3 client, string bucketName){var listObjectsV2Paginator = client.Paginators.ListObjectsV2(new ListObjectsV2Request
{
BucketName = bucketName,
});
awaitforeach (var response in listObjectsV2Paginator.Responses)
{
Console.WriteLine($"HttpStatusCode: {response.HttpStatusCode}");
Console.WriteLine($"Number of Keys: {response.KeyCount}");
foreach (var entry in response.S3Objects)
{
Console.WriteLine($"Key = {entry.Key} Size = {entry.Size}");
}
}
}
}
如需 API 詳細資訊,請參閱《AWS SDK for .NET API 參考》中的 ListObjectsV2。
################################################################################ function errecho## This function outputs everything sent to it to STDERR (standard error output).###############################################################################functionerrecho() {printf"%s\n""$*" 1>&2
}
################################################################################ function list_items_in_bucket## This function displays a list of the files in the bucket with each file's# size. The function uses the --query parameter to retrieve only the key and# size fields from the Contents collection.## Parameters:# $1 - The name of the bucket.## Returns:# The list of files in text format.# And:# 0 - If successful.# 1 - If it fails.###############################################################################functionlist_items_in_bucket() {local bucket_name=$1local response
response=$(aws s3api list-objects \
--bucket "$bucket_name" \
--output text \
--query 'Contents[].{Key: Key, Size: Size}')
# shellcheck disable=SC2181if [[ ${?} -eq 0 ]]; thenecho"$response"else
errecho "ERROR: AWS reports s3api list-objects operation failed.\n$response"return 1
fi
}
import (
"bytes""context""errors""fmt""io""log""os""time""github.com/aws/aws-sdk-go-v2/aws""github.com/aws/aws-sdk-go-v2/feature/s3/manager""github.com/aws/aws-sdk-go-v2/service/s3""github.com/aws/aws-sdk-go-v2/service/s3/types""github.com/aws/smithy-go"
)
// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions// used in the examples.// It contains S3Client, an Amazon S3 service client that is used to perform bucket// and object actions.type BucketBasics struct{
S3Client *s3.Client
}
// ListObjects lists the objects in a bucket.func(basics BucketBasics)ListObjects(ctx context.Context, bucketName string)([]types.Object, error){var err error
var output *s3.ListObjectsV2Output
input := &s3.ListObjectsV2Input{
Bucket: aws.String(bucketName),
}
var objects []types.Object
objectPaginator := s3.NewListObjectsV2Paginator(basics.S3Client, input)
for objectPaginator.HasMorePages() {
output, err = objectPaginator.NextPage(ctx)
if err != nil{var noBucket *types.NoSuchBucket
if errors.As(err, &noBucket) {
log.Printf("Bucket %s does not exist.\n", bucketName)
err = noBucket
}
break
} else{
objects = append(objects, output.Contents...)
}
}
return objects, err
}
如需 API 詳細資訊,請參閱《適用於 Go 的 AWS SDK API 參考》中的 ListObjectsV2。
/**
* Asynchronously lists all objects in the specified S3 bucket.
*
* @param bucketName the name of the S3 bucket to list objects for
* @return a {@link CompletableFuture} that completes when all objects have been listed
*/public CompletableFuture<Void> listAllObjectsAsync(String bucketName){
ListObjectsV2Request initialRequest = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(1)
.build();
ListObjectsV2Publisher paginator = getAsyncClient().listObjectsV2Paginator(initialRequest);
return paginator.subscribe(response -> {
response.contents().forEach(s3Object -> {
logger.info("Object key: " + s3Object.key());
});
}).thenRun(() -> {
logger.info("Successfully listed all objects in the bucket: " + bucketName);
}).exceptionally(ex -> {thrownew RuntimeException("Failed to list objects", ex);
});
}
使用分頁列出物件。
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
publicclassListObjectsPaginated{publicstaticvoidmain(String[] args){final String usage = """
Usage:
<bucketName>\s
Where:
bucketName - The Amazon S3 bucket from which objects are read.\s
""";
if (args.length != 1) {
System.out.println(usage);
System.exit(1);
}
String bucketName = args[0];
Region region = Region.US_EAST_1;
S3Client s3 = S3Client.builder()
.region(region)
.build();
listBucketObjects(s3, bucketName);
s3.close();
}
/**
* Lists the objects in the specified S3 bucket.
*
* @param s3 the S3Client instance used to interact with Amazon S3
* @param bucketName the name of the S3 bucket to list the objects from
*/publicstaticvoidlistBucketObjects(S3Client s3, String bucketName){try{
ListObjectsV2Request listReq = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(1)
.build();
ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq);
listRes.stream()
.flatMap(r -> r.contents().stream())
.forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size()));
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
}
如需 API 詳細資訊,請參閱《AWS SDK for Java 2.x API 參考》中的 ListObjectsV2。
classObjectWrapper:"""Encapsulates S3 object actions."""def__init__(self, s3_object):"""
:param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
that wraps object actions in a class-like structure.
"""
self.object = s3_object
self.key = self.object.key
@staticmethoddeflist(bucket, prefix=None):"""
Lists the objects in a bucket, optionally filtered by a prefix.
:param bucket: The bucket to query. This is a Boto3 Bucket resource.
:param prefix: When specified, only objects that start with this prefix are listed.
:return: The list of objects.
"""try:
ifnot prefix:
objects = list(bucket.objects.all())
else:
objects = list(bucket.objects.filter(Prefix=prefix))
logger.info(
"Got objects %s from bucket '%s'", [o.key for o in objects], bucket.name
)
except ClientError:
logger.exception("Couldn't get objects for bucket '%s'.", bucket.name)
raiseelse:
return objects
如需 API 詳細資訊,請參閱《適用於 Python (Boto3) 的AWS SDK API 參考》中的 ListObjectsV2。
TRY.
oo_result = lo_s3->listobjectsv2( " oo_result is returned for testing purposes. "
iv_bucket = iv_bucket_name
).
MESSAGE 'Retrieved list of objects in S3 bucket.'TYPE'I'.
CATCH /aws1/cx_s3_nosuchbucket.
MESSAGE 'Bucket does not exist.'TYPE'E'.
ENDTRY.
如需 API 詳細資訊,請參閱《適用於 SAP ABAP 的AWS SDK API 參考》中的 ListObjectsV2。
///<summary>/// Shows how to list the objects in an Amazon S3 bucket.///</summary>///<param name="client">An initialized Amazon S3 client object.</param>///<param name="bucketName">The name of the bucket for which to list/// the contents.</param>///<returns>A boolean value indicating the success or failure of the/// copy operation.</returns>publicstaticasync Task<bool> ListBucketContentsAsync(IAmazonS3 client, string bucketName){try{var request = new ListObjectsV2Request
{
BucketName = bucketName,
MaxKeys = 5,
};
Console.WriteLine("--------------------------------------");
Console.WriteLine($"Listing the contents of {bucketName}:");
Console.WriteLine("--------------------------------------");
ListObjectsV2Response response;
do{
response = await client.ListObjectsV2Async(request);
response.S3Objects
.ForEach(obj => Console.WriteLine($"{obj.Key,-35}{obj.LastModified.ToShortDateString(),10}{obj.Size,10}"));
// If the response is truncated, set the request ContinuationToken// from the NextContinuationToken property of the response.
request.ContinuationToken = response.NextContinuationToken;
}
while (response.IsTruncated);
returntrue;
}
catch (AmazonS3Exception ex)
{
Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' getting list of objects.");
returnfalse;
}
}
使用分頁程式列出物件。
using System;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;
///<summary>/// The following example lists objects in an Amazon Simple Storage/// Service (Amazon S3) bucket.///</summary>publicclassListObjectsPaginator{privateconststring BucketName = "amzn-s3-demo-bucket";
publicstaticasync Task Main(){
IAmazonS3 s3Client = new AmazonS3Client();
Console.WriteLine($"Listing the objects contained in {BucketName}:\n");
await ListingObjectsAsync(s3Client, BucketName);
}
///<summary>/// This method uses a paginator to retrieve the list of objects in an/// an Amazon S3 bucket.///</summary>///<param name="client">An Amazon S3 client object.</param>///<param name="bucketName">The name of the S3 bucket whose objects/// you want to list.</param>publicstaticasync Task ListingObjectsAsync(IAmazonS3 client, string bucketName){var listObjectsV2Paginator = client.Paginators.ListObjectsV2(new ListObjectsV2Request
{
BucketName = bucketName,
});
awaitforeach (var response in listObjectsV2Paginator.Responses)
{
Console.WriteLine($"HttpStatusCode: {response.HttpStatusCode}");
Console.WriteLine($"Number of Keys: {response.KeyCount}");
foreach (var entry in response.S3Objects)
{
Console.WriteLine($"Key = {entry.Key} Size = {entry.Size}");
}
}
}
}
如需 API 詳細資訊,請參閱《AWS SDK for .NET API 參考》中的 ListObjectsV2。