以编程方式列出对象键 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

以编程方式列出对象键

在 Amazon S3 中,键可以按前缀列出。您可以为相关键的名称选择通用前缀,然后使用分隔层次结构的特殊字符标记这些键。然后,您可以使用列表操作按层次选择和浏览键。这类似于在文件系统的目录中存储文件的方式。

Amazon S3 公开了列表操作,允许您列出包含在存储桶中的键。将按存储桶和前缀选择用于列表的键。例如,假设一个存储桶的名称为“dictionary”,它为每个英语词汇包含了一个键值。您可能会创建一个调用来列出该存储桶中以字母“q”开头的存储桶。列表结果始终以 UTF-8 二进制顺序返回。

SOAP 和 REST 列表操作将返回一个 XML 文档,其中包含匹配键值的名称和有关由每个键值识别的对象的信息。

注意

HTTP 上的 SOAP 支持已弃用,但 SOAP 仍可在 HTTPS 上使用。SOAP 不支持新增的 Amazon S3 功能。我们建议您使用 REST API 或 Amazon SDK,而不是使用 SOAP。

出于列表目的,可以根据通用前缀收拢那些共享一个前缀并且以特定分隔符终结的键组。这允许应用程序按层次结构组织和浏览键值,与您在文件系统的目录中组织文件的方式相同。

例如,要扩展字典存储桶以包含除英语单词外的更多内容,您可以使用语言和分隔符为每个单词添加前缀(例如,“French/logical”),从而构成键值。使用此命名方案和层级列表功能,您可以检索仅包含法语词汇的列表。您也可以浏览可用语言的顶级列表,而无需循环浏览所有按字典顺序排列的干预键。有关列表的此方面的更多信息,请参阅 使用前缀组织对象

REST API

如果您的应用程序需要它,则可以直接发送 REST 请求。您可以发送 GET 请求来返回存储桶中的某些或所有对象,或者您也可以使用选择条件来返回存储桶中对象的子集。有关更多信息,请参阅《Amazon Simple Storage Service API 参考》中的 GET Bucket (List Objects) 版本 2

列表执行效率

存储桶中的密钥总数不会对列表性能产生重大影响。它也不因是否存在 prefixmarkermaxkeysdelimiter 参数而受到影响。

循环访问多页结果

由于存储桶可以包含几乎无限数量的键,列表查询的完整结果可能会非常大。为了管理大型结果集,Amazon S3 API 支持分页,以将它们分割为多个响应。每个列出键响应将返回一个拥有多达 1000 个键的页面,同时使用指示器来指示响应是否存在截断。您可以发送一系列的列出键请求,直到您收到了所有的键。AmazonSDK 软件开发工具包包装库提供相同的分页。

示例

以下代码示例显示如何列出 S3 桶中的对象。

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

/// <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> public static async 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("--------------------------------------"); var response = new ListObjectsV2Response(); 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); return true; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' getting list of objects."); return false; } }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 ListObjects

C++
适用于 C++ 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

bool AwsDoc::S3::ListObjects(const Aws::String &bucketName, const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client s3_client(clientConfig); Aws::S3::Model::ListObjectsRequest request; request.WithBucket(bucketName); auto outcome = s3_client.ListObjects(request); if (!outcome.IsSuccess()) { std::cerr << "Error: ListObjects: " << outcome.GetError().GetMessage() << std::endl; } else { Aws::Vector<Aws::S3::Model::Object> objects = outcome.GetResult().GetContents(); for (Aws::S3::Model::Object &object: objects) { std::cout << object.GetKey() << std::endl; } } return outcome.IsSuccess(); }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 ListObjects

Go
SDK for Go V2
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// List objects in the bucket. // n.b. object keys in Amazon S3 do not begin with '/'. You do not need to lead your // prefix with it. fmt.Println("Listing the objects in the bucket:") listObjsResponse, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{ Bucket: aws.String(name), Prefix: aws.String(""), }) if err != nil { panic("Couldn't list bucket contents") } for _, object := range listObjsResponse.Contents { fmt.Printf("%s (%d bytes, class %v) \n", *object.Key, object.Size, object.StorageClass) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 ListObjects

Java
SDK for Java 2.x
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

public static void listBucketObjects(S3Client s3, String bucketName ) { try { ListObjectsRequest listObjects = ListObjectsRequest .builder() .bucket(bucketName) .build(); ListObjectsResponse res = s3.listObjects(listObjects); List<S3Object> objects = res.contents(); for (S3Object myValue : objects) { System.out.print("\n The name of the key is " + myValue.key()); System.out.print("\n The object is " + calKb(myValue.size()) + " KBs"); System.out.print("\n The owner is " + myValue.owner()); } } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } //convert bytes to kbs. private static long calKb(Long val) { return val/1024; }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 ListObjects

JavaScript
SDK for JavaScript V3
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "us-east-1"; // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

列出对象。

// Import required AWS SDK clients and commands for Node.js. import { ListObjectsCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters for the bucket export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new ListObjectsCommand(bucketParams)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

列出 1000 个或更多对象。

// Import required AWS SDK clients and commands for Node.js. import { ListObjectsCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters for the bucket export const bucketParams = { Bucket: "BUCKET_NAME" }; export async function run() { // Declare truncated as a flag that the while loop is based on. let truncated = true; // Declare a variable to which the key of the last element is assigned to in the response. let pageMarker; // while loop that runs until 'response.truncated' is false. while (truncated) { try { const response = await s3Client.send(new ListObjectsCommand(bucketParams)); // return response; //For unit tests response.Contents.forEach((item) => { console.log(item.Key); }); // Log the key of every item in the response to standard output. truncated = response.IsTruncated; // If truncated is true, assign the key of the last element in the response to the pageMarker variable. if (truncated) { pageMarker = response.Contents.slice(-1)[0].Key; // Assign the pageMarker value to bucketParams so that the next iteration starts from the new pageMarker. bucketParams.Marker = pageMarker; } // At end of the list, response.truncated is false, and the function exits the while loop. } catch (err) { console.log("Error", err); truncated = false; } } } run();
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 ListObjects

Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

suspend fun listBucketObjects(bucketName: String) { val request = ListObjectsRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> val response = s3.listObjects(request) response.contents?.forEach { myObject -> println("The name of the key is ${myObject.key}") println("The object is ${calKb(myObject.size)} KBs") println("The owner is ${myObject.owner}") } } } private fun calKb(intValue: Long): Long { return intValue / 1024 }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 ListObjects

PHP
SDK for PHP
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

列出存储桶中的对象。

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2', 'version' => 'latest']); try { $contents = $s3client->listObjects([ 'Bucket' => $bucket_name, ]); echo "The contents of your bucket are: \n"; foreach ($contents['Contents'] as $content) { echo $content['Key'] . "\n"; } } catch (Exception $exception) { echo "Failed to list objects in $bucket_name with error: " . $exception->getMessage(); exit("Please fix error with listing objects before continuing."); }
  • 有关 API 详细信息,请参阅《Amazon SDK for PHP API 参考》中的 ListObjects

Python
适用于 Python (Boto3) 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

class ObjectWrapper: """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 @staticmethod def list(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: if not 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) raise else: return objects
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 ListObjects

Ruby
SDK for Ruby
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

require "aws-sdk-s3" # Wraps Amazon S3 bucket actions. class BucketListObjectsWrapper attr_reader :bucket # @param bucket [Aws::S3::Bucket] An existing Amazon S3 bucket. def initialize(bucket) @bucket = bucket end # Lists object in a bucket. # # @param max_objects [Integer] The maximum number of objects to list. # @return [Integer] The number of objects listed. def list_objects(max_objects) count = 0 puts "The objects in #{@bucket.name} are:" @bucket.objects.each do |obj| puts "\t#{obj.key}" count += 1 break if count == max_objects end count rescue Aws::Errors::ServiceError => e puts "Couldn't list objects in bucket #{bucket.name}. Here's why: #{e.message}" 0 end end def run_demo bucket_name = "doc-example-bucket" wrapper = BucketListObjectsWrapper.new(Aws::S3::Bucket.new(bucket_name)) count = wrapper.list_objects(25) puts "Listed #{count} objects." end run_demo if $PROGRAM_NAME == __FILE__
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 ListObjects

Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

pub async fn list_objects(client: &Client, bucket_name: &str) -> Result<(), Error> { let objects = client.list_objects_v2().bucket(bucket_name).send().await?; println!("Objects in bucket:"); for obj in objects.contents().unwrap_or_default() { println!("{:?}", obj.key().unwrap()); } Ok(()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 ListObjects

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

public func listBucketFiles(bucket: String) async throws -> [String] { let input = ListObjectsV2Input( bucket: bucket ) let output = try await client.listObjectsV2(input: input) var names: [String] = [] guard let objList = output.contents else { return [] } for obj in objList { if let objName = obj.key { names.append(objName) } } return names }
  • 有关 API 详细信息,请参阅《Amazon SDK for Swift API 参考》中的 ListObjects