Este tópico descreve como listar todos os objetos em um bucket especificado, listar uma quantidade definida de objetos e obter o tamanho total dos objetos em uma pasta específica.
Informações básicas
Os objetos no OSS são organizados em ordem alfabética. Use OssClient.ListObjects para listar os objetos de um bucket. O método ListObjects aceita três formatos de parâmetros:
ListObjectOutcome ListObjects(const std::string& bucket) const: Lista os objetos de um bucket. Uma única solicitação retorna no máximo 1.000 objetos.
ListObjectOutcome ListObjects(const std::string& bucket, const std::string& prefix) const: Lista os objetos com um prefixo específico dentro de um bucket. O limite por solicitação também é de 1.000 objetos.
ListObjectOutcome ListObjects(const ListObjectsRequest& request) const: Oferece diversos recursos de filtragem para consultas flexíveis.
A tabela a seguir detalha os principais parâmetros.
|
Parâmetro |
Descrição |
|
delimiter |
Caractere usado para agrupar nomes de objetos. Todos os objetos cujos nomes contêm o prefixo especificado e aparecem entre esse prefixo e a primeira ocorrência do delimitador são agrupados como um conjunto (commonPrefixes). |
|
prefix |
Define que apenas os objetos com o prefixo indicado devem ser retornados. |
|
maxKeys |
Quantidade máxima de objetos a retornar nesta solicitação. O valor padrão é 100 e o máximo permitido é 1.000. |
|
marker |
Lista os objetos que aparecem após o marcador especificado. |
Observações
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Os exemplos demonstram a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Criar uma instância OssClient.
Para listar objetos, é necessária a permissão
oss:ListObjects. Para mais informações, consulte Conceder uma política personalizada.
Listar objetos
O código abaixo exemplifica como listar os objetos de um bucket específico. Por padrão, o sistema retorna 100 objetos.
#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);
/* List objects. */
ListObjectsRequest request(BucketName);
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;
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;
}
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
Listar uma quantidade específica de objetos
O exemplo a seguir mostra como limitar o número de objetos retornados na listagem.
#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);
/* List objects. */
ListObjectsRequest request(BucketName);
/* Set the maximum number of objects to list to 200. */
request.setMaxKeys(200);
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;
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;
}
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
Listar objetos e subpastas em uma pasta especificada
O trecho de código abaixo ilustra como listar tanto os objetos quanto as subpastas dentro de um diretório específico:
#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";
/* Specify the prefix of the objects to list. */
std::string keyPrefix = "yourkeyPrefix";
/* 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);
/* Set the forward slash (/) as the folder separator. */
request.setDelimiter("/");
request.setPrefix(keyPrefix);
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;
break;
}
for (const auto& object : outcome.result().ObjectSummarys()) {
std::cout << "object"<<
",name:" << object.Key() <<
",size:" << object.Size() <<
",last modified time:" << object.LastModified() << std::endl;
}
for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
std::cout << "commonPrefix" << ",name:" << commonPrefix << std::endl;
}
nextMarker = outcome.result().NextMarker();
isTruncated = outcome.result().IsTruncated();
} while (isTruncated);
/* Release network resources. */
ShutdownSdk();
return 0;
}
Listar o tamanho dos objetos em uma pasta especificada
Use o código a seguir para calcular o tamanho total ocupado pelos objetos dentro de uma pasta:
#include <iostream>
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
static int64_t calculateFolderLength(const OssClient &client, const std::string &bucketName, const std::string &folder)
{
std::string nextMarker = "";
bool isTruncated = false;
int64_t size = 0;
do {
/* List objects. */
ListObjectsRequest request(bucketName);
request.setPrefix(folder);
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;
break;
}
for (const auto& object : outcome.result().ObjectSummarys()) {
size += object.Size();
}
nextMarker = outcome.result().NextMarker();
isTruncated = outcome.result().IsTruncated();
} while (isTruncated);
return size;
}
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";
/* Specify the prefix of the objects to list. */
std::string keyPrefix = "yourkeyPrefix";
/* 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);
/* Set the forward slash (/) as the folder separator. */
request.setDelimiter("/");
request.setPrefix(keyPrefix);
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;
break;
}
for (const auto& object : outcome.result().ObjectSummarys()) {
std::cout << "object" <<
",name:" << object.Key() <<
",size:" << object.Size() << std::endl;
}
for (const auto& commonPrefix : outcome.result().CommonPrefixes()) {
int64_t foldersize = calculateFolderLength(client, BucketName, commonPrefix);
std::cout << "folder" <<
",name:" << commonPrefix <<
",size:" << foldersize << std::endl;
}
nextMarker = outcome.result().NextMarker();
isTruncated = outcome.result().IsTruncated();
} while (isTruncated);
/* Release network resources. */
ShutdownSdk();
return 0;
}
Listar objetos com um prefixo específico
Veja abaixo como listar apenas os objetos que possuem determinado prefixo.
#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";
/* Specify the prefix of the objects to list. */
std::string keyPrefix = "yourkeyPrefix";
/* 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.setPrefix(keyPrefix);
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;
break;
}
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;
}
Listar objetos após um marcador especificado
O parâmetro marker define um nome de objeto como ponto de partida. O código a seguir demonstra como listar os objetos que aparecem depois desse marcador.
#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";
/* Set the marker. */
std::string YourMarker = "yourMarker";
/* 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);
ListObjectOutcome outcome;
do {
/* List objects. */
ListObjectsRequest request(BucketName);
/* List objects that appear after the specified marker. */
request.setMarker(YourMarker);
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;
break;
}
YourMarker = outcome.result().NextMarker();
for (const auto& object : outcome.result().ObjectSummarys()) {
std::cout << "object"<<
",name:" << object.Key() <<
",size:" << object.Size() <<
",last modified time:" << object.LastModified() << std::endl;
}
} while (outcome.result().IsTruncated());
/* Release network resources. */
ShutdownSdk();
return 0;
}
Especificar a codificação dos nomes dos objetos
Quando o nome de um objeto contém caracteres especiais, aplique codificação URL para transmissão. O OSS suporta exclusivamente codificação URL.
Aspas simples (')
Aspas duplas ("")
E comercial (&)
Sinais de maior e menor que (< >)
Caracteres chineses
O exemplo abaixo mostra como definir a codificação para os nomes dos objetos:
#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) ;
/* Specify the encoding of object names. */
request.setEncodingType("url");
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;
break;
}
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;
}
Recurso de pastas
O OSS não possui o conceito nativo de pastas; todos os elementos são armazenados como objetos. Criar uma pasta equivale a criar um objeto de zero bytes cujo nome termina com barra (/). Esse objeto pode ser enviado e baixado normalmente. O console do OSS exibe objetos terminados em barra (/) como pastas.
Use os parâmetros delimiter e prefix para listar objetos por diretório.
Ao definir prefix como o nome de um diretório na solicitação, o sistema lista os objetos e subdiretórios cujos nomes contenham esse prefixo.
Se você especificar um prefixo e definir delimiter como barra (/) na solicitação, a lista incluirá objetos e subdiretórios cujos nomes comecem com o prefixo indicado naquele diretório. Cada subdiretório aparece como um único elemento de resultado em CommonPrefixes. Objetos e diretórios dentro desses subdiretórios não são listados.
Por exemplo, considere um bucket contendo os seguintes objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi e fun/movie/007.avi. A barra (/) é usada como delimitador de diretório. Os exemplos a seguir mostram como listar objetos em diretórios simulados.
-
Listar todos os objetos em um bucket
O código abaixo exemplifica como listar todos os objetos de um bucket específico.
#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; }Resultado retornado:
Objects: fun/movie/001.avi fun/movie/007.avi fun/test.jpg oss.jpg CommonPrefixes: -
Listar todos os objetos em uma pasta especificada
Este exemplo demonstra como listar todos os objetos dentro de uma pasta específica.
#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.setPrefix("fun/"); 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; break; } for (const auto& object : outcome.result().ObjectSummarys()) { std::cout << "object"<< ",name:" << object.Key() << ",size:" << object.Size() << ",last modified time:" << object.LastModified() << std::endl; } for (const auto& commonPrefix : outcome.result().CommonPrefixes()) { std::cout << "commonPrefix" << ",name:" << commonPrefix << std::endl; } nextMarker = outcome.result().NextMarker(); isTruncated = outcome.result().IsTruncated(); } while (isTruncated); /* Release network resources. */ ShutdownSdk(); return 0; }Resultado retornado:
Objects: fun/movie/001.avi fun/movie/007.avi fun/test.jpg CommonPrefixes: -
Listar objetos e subpastas em uma pasta
O código a seguir mostra como listar objetos e subpastas dentro de um diretório definido.
#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); /* Set the forward slash (/) as the folder separator. */ request.setDelimiter("/"); request.setPrefix("fun/"); 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; break; } for (const auto& object : outcome.result().ObjectSummarys()) { std::cout << "object"<< ",name:" << object.Key() << ",size:" << object.Size() << ",last modified time:" << object.LastModified() << std::endl; } for (const auto& commonPrefix : outcome.result().CommonPrefixes()) { std::cout << "commonPrefix" << ",name:" << commonPrefix << std::endl; } nextMarker = outcome.result().NextMarker(); isTruncated = outcome.result().IsTruncated(); } while (isTruncated); /* Release network resources. */ ShutdownSdk(); return 0; }Resultado retornado:
Objects: fun/test.jpg CommonPrefixes: fun/movie/ -
Listar o tamanho dos objetos em uma pasta especificada
Use este exemplo para obter o tamanho total dos objetos em uma pasta específica:
#include <alibabacloud/oss/OssClient.h> using namespace AlibabaCloud::OSS; static int64_t calculateFolderLength (const OssClient &client, const std::string &bucketName, const std::string &folder) { std::string nextMarker = ""; bool isTruncated = false; int64_t size = 0; do { /* List objects. */ ListObjectsRequest request(bucketName); request.setPrefix(folder); 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; break; } for (const auto& object : outcome.result().ObjectSummarys()) { size += object.Size(); } nextMarker = outcome.result().NextMarker(); isTruncated = outcome.result().IsTruncated(); } while (isTruncated); return size; } 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); /* Set the forward slash (/) as the folder separator. */ request.setDelimiter("/"); request.setPrefix("fun/"); 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; break; } for (const auto& object : outcome.result().ObjectSummarys()) { std::cout << "object" << ",name:" << object.Key() << ",size:" << object.Size() << std::endl; } for (const auto& commonPrefix : outcome.result().CommonPrefixes()) { int64_t foldersize = calculateFolderLength(client, BucketName, commonPrefix); std::cout << "folder" << ",name:" << commonPrefix << ",size:" << foldersize << std::endl; } nextMarker = outcome.result().NextMarker(); isTruncated = outcome.result().IsTruncated(); } while (isTruncated); /* Release network resources. */ ShutdownSdk(); return 0; }
Referências
Para acessar o código de exemplo completo sobre listagem de objetos, consulte o exemplo no GitHub.
Para mais detalhes sobre as operações de API usadas para listar objetos, consulte GetBucket (ListObjects) e ListObjectsV2 (GetBucketV2).