Elenco delle chiavi oggetto a livello di programmazione
In Amazon S3, le chiavi possono essere elencate per prefisso. È possibile scegliere un prefisso comune per i nomi delle chiavi correlate e contrassegnare queste chiavi con un carattere speciale che delimita la gerarchia. È quindi possibile utilizzare l'operazione elenco per selezionare e sfogliare le chiavi gerarchicamente. Questa operazione è simile all'archiviazione dei file in directory all'interno di un file system.
Amazon S3 visualizza un'operazione di elenco che consente di elencare le chiavi contenute in un bucket. Le chiavi vengono selezionate per l'elenco in base al bucket e al prefisso. Ad esempio, si prenda in considerazione un bucket denominato "dictionary
" contenente una chiave per ogni parola inglese. È possibile eseguire una chiamata per elencare tutte le chiavi in tale bucket che iniziano con la lettera "q". I risultati dell'elenco vengono sempre restituiti in ordine binario UTF-8.
Sia le operazioni di elenco SOAP che quelle REST restituiscono un documento XML contenente i nomi delle chiavi corrispondenti e informazioni sull'oggetto identificato da ciascuna chiave.
Il supporto di SOAP su HTTP non viene più utilizzato ma è ancora disponibile su HTTPS. Le nuove funzioni di Amazon S3 non sono supportate per SOAP. Invece di utilizzare SOAP, si consiglia di utilizzare REST API o gli SDK AWS.
È possibile raggruppare i gruppi di chiavi che condividono un prefisso che termina con un delimitatore speciale in base al prefisso comune a scopo di elenco. Ciò consente alle applicazioni di organizzare ed esplorare le chiavi in ordine gerarchico, in modo simile all'organizzazione dei file in directory in un file system.
Ad esempio, per estendere il bucket dictionary in modo che contenga altre parole oltre a quelle inglesi, è possibile creare chiavi anteponendo a ciascuna parola un prefisso insieme alla lingua e a un delimitatore, ad esempio "French/logical
". È possibile utilizzare questo schema di denominazione e la funzione di elenco gerarchico per recuperare un elenco costituito solo dalle parole francesi. È inoltre possibile sfogliare l'elenco di livello superiore delle lingue disponibili senza dover scorrere tutte le chiavi utilizzate in ordine lessicografico. Per ulteriori informazioni su questo tipo di elenco, consulta Organizzazione degli oggetti utilizzando i prefissi.
REST API
Tuttavia, se l'applicazione lo richiede, è possibile inviare richieste REST direttamente. È possibile inviare una richiesta GET per restituire alcuni o tutti gli oggetti in un bucket oppure è possibile utilizzare le policy di selezione per restituire un sottoinsieme degli oggetti in un bucket. Per ulteriori informazioni, consulta l'argomento relativo all'operazione GET Bucket (List Objects) Version 2 nella Documentazione di riferimento delle API di Amazon Simple Storage Service.
Efficacia dell'implementazione degli elenchi
Le prestazioni dell'elenco non sono influenzate in modo sostanziale dal numero totale di chiavi nel bucket. Inoltre, non sono influenzate dalla presenza o dall'assenza degli argomenti delimiter
, prefix
, marker
o maxkeys
.
Scorrimento dei risultati di più pagine
Poiché i bucket possono contenere un numero potenzialmente illimitato di chiavi, una query di elenco può restituire un numero estremamente elevato di risultati. Per gestire set di risultati di grandi dimensioni, l'API di Amazon S3 supporta la paginazione per suddividerli in più risposte. Ciascuna risposta delle chiavi di elenco restituisce una pagina contenente fino a 1000 chiavi con un indicatore che specifica se la risposta è troncata. È possibile inviare una serie di richieste di elenchi di chiavi finché non si ricevono tutte le chiavi. AWS Le librerie wrapper dell'SDK forniscono la stessa paginazione.
Esempi
Gli esempi di codice seguenti mostrano come elencare gli oggetti in un bucket S3.
- .NET
-
- AWS SDK for .NET
-
/// <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;
}
}
- C++
-
- SDK per C++
-
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();
}
- Go
-
- SDK per Go V2
-
// 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)
}
- Java
-
- SDK per Java 2.x
-
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;
}
- JavaScript
-
- SDK per JavaScript v3
-
Crea il client.
// 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 };
Elenca gli oggetti.
// 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();
Elenca 1000 o più oggetti.
// 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();
- Kotlin
-
- SDK per Kotlin
-
Si tratta di una documentazione di pre-rilascio di una caratteristica nella versione di anteprima ed è soggetta a modifiche.
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
}
- PHP
-
- SDK per PHP
-
Elenca gli oggetti in un bucket.
$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.");
}
- Python
-
- SDK per Python (Boto3)
-
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
- Ruby
-
- SDK per Ruby
-
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__
- Rust
-
- SDK per Rust
-
Questa documentazione è per un SDK in anteprima. L'SDK è soggetto a modifiche e non deve essere usato in ambiente di produzione.
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(())
}
- Swift
-
- SDK per Swift
-
Si tratta di una documentazione di pre-rilascio di un SDK nella versione di anteprima. ed è soggetta a modifiche.
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
}