Este tópico descreve como listar todos os objetos, um número específico de objetos e objetos cujos nomes contêm um prefixo específico em um bucket do Object Storage Service (OSS).
Observações de uso
Este tópico utiliza 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 obter detalhes sobre as regiões e endpoints compatíveis, consulte Regiões e endpoints.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar-se com credenciais do Security Token Service (STS), consulte Criar um OssClient.
Para listar objetos, é necessária a permissão
oss:ListObjects. Para mais informações, consulte Anexar uma política personalizada a um usuário RAM.
Listar objetos
Chame o método listObjects ou listObjectsV2 para listar objetos no diretório raiz de um bucket especificado. Subdiretórios e objetos dentro desses subdiretórios não são listados.
-
Uso do método listObjects
O código a seguir mostra como chamar o método listObjects para listar objetos no diretório raiz de um bucket chamado examplebucket. Subdiretórios e objetos neles contidos não são listados. Por padrão, 100 objetos são retornados.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\Core\OssException; try { // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); $listObjectInfo = $ossClient->listObjects($bucket); printf("Bucket Name: %s". "\n",$listObjectInfo->getBucketName()); printf("Prefix: %s". "\n",$listObjectInfo->getPrefix()); printf("Marker: %s". "\n",$listObjectInfo->getMarker()); printf("Next Marker: %s". "\n",$listObjectInfo->getNextMarker()); printf("Max Keys: %s". "\n",$listObjectInfo->getMaxKeys()); printf("Delimiter: %s". "\n",$listObjectInfo->getDelimiter()); printf("Is Truncated: %s". "\n",$listObjectInfo->getIsTruncated()); $objectList = $listObjectInfo->getObjectList(); $prefixList = $listObjectInfo->getPrefixList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { printf("Object Name: %s". "\n",$objectInfo->getKey()); printf("Object Size: %s". "\n",$objectInfo->getSize()); printf("Object Type: %s". "\n",$objectInfo->getType()); printf("Object ETag: %s". "\n",$objectInfo->getETag()); printf("Object Last Modified: %s". "\n",$objectInfo->getLastModified()); printf("Object Storage Class: %s". "\n",$objectInfo->getStorageClass()); if ($objectInfo->getRestoreInfo()){ printf("Restore Info: %s". "\n",$objectInfo->getRestoreInfo() ); } if($objectInfo->getOwner()){ printf("Owner Id:".$objectInfo->getOwner()->getId() . "\n"); printf("Owner Name:".$objectInfo->getOwner()->getDisplayName() . "\n"); } } } if (!empty($prefixList)) { print("prefixList: \n"); foreach ($prefixList as $prefixInfo) { printf("Common Prefix:%s\n",$prefixInfo->getPrefix()); } } } catch (OssException $e) { printf($e->getMessage() . "\n"); return; } -
Método listObjectsV2
O código abaixo exemplifica o uso do método listObjectsV2 para listar objetos no diretório raiz de um bucket chamado examplebucket. Esta operação não lista subdiretórios nem os objetos dentro deles. Por padrão, até 100 objetos são retornados.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\Core\OssException; try { // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); $listObjectInfo = $ossClient->listObjectsV2($bucket); printf("Bucket Name: %s". "\n",$listObjectInfo->getBucketName()); printf("Prefix: %s". "\n",$listObjectInfo->getPrefix()); printf("Next Continuation Token: %s". "\n",$listObjectInfo->getNextContinuationToken()); printf("Continuation Token: %s". "\n",$listObjectInfo->getContinuationToken()); printf("Max Keys: %s". "\n",$listObjectInfo->getMaxKeys()); printf("Key Count: %s". "\n",$listObjectInfo->getKeyCount()); printf("Delimiter: %s". "\n",$listObjectInfo->getDelimiter()); printf("Is Truncated: %s". "\n",$listObjectInfo->getIsTruncated()); printf("Start After: %s". "\n",$listObjectInfo->getStartAfter()); $objectList = $listObjectInfo->getObjectList(); $prefixList = $listObjectInfo->getPrefixList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { printf("Object Name: %s". "\n",$objectInfo->getKey()); printf("Object Size: %s". "\n",$objectInfo->getSize()); printf("Object Type: %s". "\n",$objectInfo->getType()); printf("Object ETag: %s". "\n",$objectInfo->getETag()); printf("Object Last Modified: %s". "\n",$objectInfo->getLastModified()); printf("Object Storage Class: %s". "\n",$objectInfo->getStorageClass()); if ($objectInfo->getRestoreInfo()){ printf("Restore Info: %s". "\n",$objectInfo->getRestoreInfo() ); } if($objectInfo->getOwner()){ printf("Owner Id:".$objectInfo->getOwner()->getId() . "\n"); printf("Owner Name:".$objectInfo->getOwner()->getDisplayName() . "\n"); } } } if (!empty($prefixList)) { print("prefixList: \n"); foreach ($prefixList as $prefixInfo) { printf("Common Prefix:%s\n",$prefixInfo->getPrefix()); } } } catch (OssException $e) { printf($e->getMessage() . "\n"); return; }
Listar um número especificado de objetos
Utilize o método listObjects ou listObjectsV2 para listar uma quantidade definida de objetos em um bucket.
-
Uso do método listObjects
O exemplo de código a seguir chama o método listObjects para listar 200 objetos em um bucket chamado examplebucket.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the maximum number of objects to return to 200. $maxkeys = 200; $options = array( 'max-keys' => $maxkeys, ); try { $listObjectInfo = $ossClient->listObjects($bucket, $options); } catch (OssException $e) { printf($e->getMessage() . "\n"); return; } $objectList = $listObjectInfo->getObjectList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } } -
Uso do método listObjectsV2
O trecho de código abaixo demonstra como chamar o método listObjectsV2 para listar 200 objetos em um bucket chamado examplebucket.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the maximum number of objects to return to 200. $maxkeys = 200; $options = array( 'max-keys' => $maxkeys, ); try { $listObjectInfo = $ossClient->listObjectsV2($bucket, $options); } catch (OssException $e) { printf($e->getMessage() . "\n"); return; } $objectList = $listObjectInfo->getObjectList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } }
Listar objetos com um prefixo especificado
Chame o método listObjects ou listObjectsV2 para listar objetos que possuem um prefixo definido em um bucket.
-
Uso do método listObjects
O código seguinte ilustra como usar o método listObjects para listar objetos com o prefixo
direm um bucket chamado examplebucket.<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the prefix to dir/. $prefix = 'dir/'; $options = array( 'prefix' => $prefix, ); try { $listObjectInfo = $ossClient->listObjects($bucket, $options); } catch (OssException $e) { printf($e->getMessage() . "\n"); return; } $objectList = $listObjectInfo->getObjectList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } } -
Uso do método listObjectsV2
Veja abaixo como chamar o método listObjectsV2 para listar objetos com o prefixo
direm um bucket chamado examplebucket.<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the prefix to dir/. $prefix = 'dir/'; $options = array( 'prefix' => $prefix, ); try { $listObjectInfo = $ossClient->listObjectsV2($bucket, $options); } catch (OssException $e) { printf($e->getMessage() . "\n"); return; } $objectList = $listObjectInfo->getObjectList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } }
Listar objetos em ordem alfabética após um nome de objeto especificado
Chame o método listObjects ou listObjectsV2 para listar objetos que aparecem em ordem alfabética após um nome de objeto determinado.
-
Uso do método listObjects
O código a seguir demonstra como chamar o método listObjects para listar objetos posicionados alfabeticamente depois de
test.txtem um bucket chamado examplebucket.<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set marker to test.txt. This parameter specifies that objects are returned in alphabetical order starting from the object specified by marker. $marker = "test.txt"; $options = array( OssClient::OSS_MARKER=>$marker ); try { $listObjectInfo = $ossClient->listObjects($bucket, $options); } catch (OssException $e) { printf($e->getMessage() . "\n"); return; } $objectList = $listObjectInfo->getObjectList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } } -
Uso do método listObjectsV2
O exemplo abaixo mostra como usar o método listObjectsV2 para listar objetos posicionados alfabeticamente após
test.txtem um bucket chamado examplebucket.<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set startAfter to test.txt. This parameter specifies that objects are returned in alphabetical order starting from the object specified by startAfter. $startAfter = "test.txt"; $options = array( OssClient::OSS_START_AFTER=>$startAfter ); try { $listObjectInfo = $ossClient->listObjectsV2($bucket, $options); } catch (OssException $e) { printf($e->getMessage() . "\n"); return; } $objectList = $listObjectInfo->getObjectList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } }
Listar todos os objetos por página
Use o método listObjects ou listObjectsV2 para listar todos os objetos de forma paginada. Utilize o parâmetro maxKeys para definir a quantidade de objetos retornados em cada página.
-
Uso do método listObjects
O código a seguir exemplifica a chamada do método listObjects para listar todos os objetos de um bucket chamado examplebucket de maneira paginada.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); $options = array( // Set the number of objects to return on each page to 200. OssClient::OSS_MAX_KEYS=>200 ); do{ $result = $ossClient->listObjects($bucket,$options); $objectList = $result->getObjectList(); print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } $options[OssClient::OSS_MARKER] = $result->getNextMarker(); }while($result->getIsTruncated() === 'true'); -
Uso do método listObjectsV2
O trecho de código abaixo mostra como utilizar o método listObjectsV2 para listar paginadamente todos os objetos em um bucket chamado examplebucket.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); $options = array( // Set the number of objects to return on each page to 200. OssClient::OSS_MAX_KEYS=>200 ); do{ $result = $ossClient->listObjectsV2($bucket,$options); $objectList = $result->getObjectList(); print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } $options[OssClient::OSS_CONTINUATION_TOKEN] = $result->getNextContinuationToken(); }while($result->getIsTruncated() === 'true');
Listar objetos com um prefixo especificado por página
Para listar objetos com um prefixo específico de forma paginada, chame o método listObjects ou listObjectsV2.
-
Uso do método listObjects
O código a seguir demonstra como chamar o método listObjects para listar, paginação por paginação, os objetos com o prefixo
direm um bucket chamado examplebucket.<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the number of objects to return on each page to 100. $maxKeys = 100; // Specify the prefix. Example: dir/. $prefix = 'dir/'; $options = array( OssClient::OSS_MAX_KEYS =>$maxKeys, OssClient::OSS_PREFIX =>$prefix ); do{ $result = $ossClient->listObjects($bucket,$options); $objectList = $result->getObjectList(); print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } $options[OssClient::OSS_MARKER] = $result->getNextMarker(); }while($result->getIsTruncated() === 'true'); -
Uso do método listObjectsV2
Veja a seguir como usar o método listObjectsV2 para listar objetos com o prefixo
direm um bucket chamado examplebucket, utilizando paginação.<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the number of objects to return on each page to 100. $maxKeys = 100; // Specify the prefix. Example: dir/. $prefix = 'dir/'; $options = array( OssClient::OSS_MAX_KEYS =>$maxKeys, OssClient::OSS_PREFIX =>$prefix ); do{ $result = $ossClient->listObjectsV2($bucket,$options); $objectList = $result->getObjectList(); print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } $options[OssClient::OSS_CONTINUATION_TOKEN] = $result->getNextContinuationToken(); }while($result->getIsTruncated() === 'true');
Especificar a codificação dos nomes dos objetos
Caso o nome de um objeto contenha caracteres especiais, codifique-o para transmissão. O OSS oferece suporte apenas à codificação URL.
Aspas simples (')
Aspas duplas (")
E comercial (&)
Sinais de maior e menor que (< >)
Vírgulas de enumeração (、)
Caracteres chineses
Chame o método listObjects ou listObjectsV2 para especificar a codificação dos nomes dos objetos.
-
Uso do método listObjects
O código a seguir mostra como chamar o método listObjects para definir a codificação dos nomes dos objetos.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); $options = array( // Set the encoding type of object names to URL. OssClient::OSS_ENCODING_TYPE=>'url', // Set the number of objects to return on each page to 20. OssClient::OSS_MAX_KEYS=>20 ); do{ $result = $ossClient->listObjects($bucket,$options); $objectList = $result->getObjectList(); print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } print("prefix:\n"); $prefixList = $result->getPrefixList(); foreach ($prefixList as $prefixInfo) { print($prefixInfo->getPrefix() . "\n"); } if($result->getDelimiter() != null){ printf("delimiter:".$result->getDelimiter().PHP_EOL); } if($result->getMarker() != null){ printf("marker:".$result->getMarker().PHP_EOL); } $options[OssClient::OSS_MARKER] = $result->getNextMarker(); }while($result->getIsTruncated() === 'true'); -
Uso do método listObjectsV2
O exemplo abaixo ilustra como chamar o método listObjectsV2 para especificar a codificação dos nomes dos objetos.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); $options = array( // Set the encoding type of object names to URL. OssClient::OSS_ENCODING_TYPE=>'url', // Set the number of objects to return on each page to 20. OssClient::OSS_MAX_KEYS=>20 ); do{ $result = $ossClient->listObjectsV2($bucket,$options); $objectList = $result->getObjectList(); print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } print("prefix:\n"); $prefixList = $result->getPrefixList(); foreach ($prefixList as $prefixInfo) { print($prefixInfo->getPrefix() . "\n"); } if($result->getDelimiter() != null){ printf("delimiter:".$result->getDelimiter().PHP_EOL); } if($result->getStartAfter() != null){ printf("start after:".$result->getStartAfter().PHP_EOL); } $options[OssClient::OSS_CONTINUATION_TOKEN] = $result->getNextContinuationToken(); }while($result->getIsTruncated() === 'true');
Simular diretórios
O OSS utiliza uma estrutura plana onde todos os dados são armazenados como objetos. Para simular um diretório, crie um objeto de 0 byte cujo nome termine com uma barra (/). Esse objeto pode ser enviado e baixado normalmente. O console do OSS exibe objetos cujos nomes terminam com barra (/) como diretórios.
Especifique os parâmetros delimiter e prefix para listar objetos por diretório.
Se você definir prefix como o nome de um diretório na solicitação, os objetos e subdiretórios cujos nomes contêm esse prefix serão listados.
Ao especificar um prefix e definir delimiter como barra (/) na solicitação, apenas os objetos e subdiretórios cujos nomes começam com o prefixo especificado naquele diretório serão listados. Cada subdiretório aparece como um único elemento de resultado em CommonPrefixes. Os objetos e diretórios dentro desses subdiretórios não são listados.
Por exemplo, suponha que um bucket contenha os seguintes objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi e fun/movie/007.avi. A barra (/) é especificada como delimitador de diretório. Os exemplos a seguir descrevem como listar objetos em diretórios simulados.
Listar todos os objetos em um bucket
Chame o método listObjects ou listObjectsV2 para listar todos os objetos em um bucket especificado.
-
Uso do método listObjects
O código a seguir mostra como chamar o método listObjects para listar todos os objetos em um bucket chamado examplebucket.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } require_once __DIR__ . '/Common.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); $options = array( 'delimiter' => '', ); try { $listObjectInfo = $ossClient->listObjects($bucket,$options); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": OK" . "\n"); $objectList = $listObjectInfo->getObjectList(); $prefixList = $listObjectInfo->getPrefixList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } } if (!empty($prefixList)) { print("prefixList: \n"); foreach ($prefixList as $prefixInfo) { print($prefixInfo->getPrefix() . "\n"); } } -
Uso do método listObjectsV2
O código a seguir demonstra como chamar o método listObjectsV2 para listar todos os objetos em um bucket chamado examplebucket.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } require_once __DIR__ . '/Common.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); $options = array( 'delimiter' => '', ); try { $listObjectInfo = $ossClient->listObjectsV2($bucket,$options); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": OK" . "\n"); $objectList = $listObjectInfo->getObjectList(); $prefixList = $listObjectInfo->getPrefixList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } } if (!empty($prefixList)) { print("prefixList: \n"); foreach ($prefixList as $prefixInfo) { print($prefixInfo->getPrefix() . "\n"); } } -
Resposta
A resposta a seguir é retornada ao chamar os métodos acima para listar todos os objetos no bucket examplebucket.
objectList: fun/movie/001.avi fun/movie/007.avi fun/test.jpg oss.jpg
Listar todos os objetos em um diretório especificado
Chame o método listObjects ou listObjectsV2 para listar todos os objetos no diretório fun/.
-
Uso do método listObjects
O código a seguir mostra como chamar o método listObjects para listar todos os objetos no diretório fun/.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } require_once __DIR__ . '/Common.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the directory to fun/. $prefix = 'fun/'; $options = array( 'prefix' => $prefix, 'delimiter' => '', ); try { $listObjectInfo = $ossClient->listObjects($bucket, $options); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": OK" . "\n"); $objectList = $listObjectInfo->getObjectList(); $prefixList = $listObjectInfo->getPrefixList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } } if (!empty($prefixList)) { print("prefixList: \n"); foreach ($prefixList as $prefixInfo) { print($prefixInfo->getPrefix() . "\n"); } } -
Uso do método listObjectsV2
O código a seguir demonstra como chamar o método listObjectsV2 para listar todos os objetos no diretório fun/.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } require_once __DIR__ . '/Common.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the directory name to fun/. $prefix = 'fun/'; $options = array( 'prefix' => $prefix, 'delimiter' => '', ); try { $listObjectInfo = $ossClient->listObjectsV2($bucket, $options); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": OK" . "\n"); $objectList = $listObjectInfo->getObjectList(); $prefixList = $listObjectInfo->getPrefixList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } } if (!empty($prefixList)) { print("prefixList: \n"); foreach ($prefixList as $prefixInfo) { print($prefixInfo->getPrefix() . "\n"); } } -
Resultados
A resposta a seguir é retornada ao chamar os métodos acima para listar todos os objetos no diretório fun/.
objectList: fun/movie/001.avi fun/movie/007.avi fun/test.jpg
Listar objetos e subdiretórios em um diretório
Chame o método listObjects ou listObjectsV2 para listar objetos e subdiretórios no diretório fun/.
-
Uso do método listObjects
O código a seguir mostra como chamar o método listObjects para listar objetos e subdiretórios no diretório fun/.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } require_once __DIR__ . '/Common.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the directory name to fun/. $prefix = 'fun/'; $delimiter = '/'; $options = array( 'delimiter' => $delimiter, 'prefix' => $prefix, ); try { $listObjectInfo = $ossClient->listObjects($bucket, $options); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": OK" . "\n"); $objectList = $listObjectInfo->getObjectList(); $prefixList = $listObjectInfo->getPrefixList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } } // The commonPrefixs list contains all subdirectories in the fun/ directory. if (!empty($prefixList)) { print("prefixList: \n"); foreach ($prefixList as $prefixInfo) { print($prefixInfo->getPrefix() . "\n"); } } -
Uso do método listObjectsV2
O código a seguir demonstra como chamar o método listObjectsV2 para listar objetos e subdiretórios no diretório fun/.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } require_once __DIR__ . '/Common.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the directory name to fun/. $prefix = 'fun/'; $delimiter = '/'; $options = array( 'delimiter' => $delimiter, 'prefix' => $prefix, ); try { $listObjectInfo = $ossClient->listObjectsV2($bucket, $options); } catch (OssException $e) { printf(__FUNCTION__ . ": FAILED\n"); printf($e->getMessage() . "\n"); return; } print(__FUNCTION__ . ": OK" . "\n"); $objectList = $listObjectInfo->getObjectList(); $prefixList = $listObjectInfo->getPrefixList(); if (!empty($objectList)) { print("objectList:\n"); foreach ($objectList as $objectInfo) { print($objectInfo->getKey() . "\n"); } } // The commonPrefixs list contains all subdirectories in the fun/ directory. if (!empty($prefixList)) { print("prefixList: \n"); foreach ($prefixList as $prefixInfo) { print($prefixInfo->getPrefix() . "\n"); } } -
Valor de retorno
A resposta a seguir é retornada ao chamar os métodos acima para listar objetos e subdiretórios no diretório fun/.
objectList: fun/test.jpg prefixList: fun/movie/
Obter o tamanho dos objetos em um diretório especificado
Chame o método listObjects ou listObjectsV2 para obter o tamanho dos objetos no diretório fun/.
-
Uso do método listObjects
O código a seguir mostra como chamar o método listObjects para obter o tamanho dos objetos no diretório fun/.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } require_once __DIR__ . '/Common.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the directory name to fun/. $prefix = 'fun/'; $delimiter = ''; $nextMarker = ''; $maxkeys = 1000; $options = array( 'delimiter' => $delimiter, 'prefix' => $prefix, 'max-keys' => $maxkeys, 'marker' => $nextMarker, ); $bool = true; $size = 0; while ($bool){ $result = $ossClient->listObjects($bucket,$options); foreach ($result->getObjectList() as $objInfo){ printf("object name".$objInfo->getKey().":" . ($objInfo->getSize() / 1024) . "KB".PHP_EOL); $size+=$objInfo->getSize(); } if($result->getIsTruncated() === 'true'){ $options['marker'] = $result->getNextMarker(); }else{ $bool = false; } } printf($prefix.":" . ($size / 1024) . "KB".PHP_EOL); -
Uso do método listObjectsV2
O código a seguir demonstra como chamar o método listObjectsV2 para obter o tamanho dos objetos no diretório fun/.
<?php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } require_once __DIR__ . '/Common.php'; use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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. $provider = new EnvironmentVariableCredentialsProvider(); // The following example uses the endpoint of the China (Hangzhou) region. Replace the endpoint with the actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the bucket name. Example: examplebucket. $bucket= "examplebucket"; $config = array( "provider" => $provider, "endpoint" => $endpoint, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $ossClient = new OssClient($config); // Set the directory name to fun/. $prefix = 'fun/'; $delimiter = ''; $nextMarker = ''; $maxkeys = 1000; $options = array( 'delimiter' => $delimiter, 'prefix' => $prefix, 'max-keys' => $maxkeys, ); $bool = true; $size = 0; while ($bool){ $result = $ossClient->listObjectsV2($bucket,$options); foreach ($result->getObjectList() as $objInfo){ printf("object name".$objInfo->getKey().":" . ($objInfo->getSize() / 1024) . "KB".PHP_EOL); $size+=$objInfo->getSize(); } if($result->getIsTruncated() === 'true'){ $options[OssClient::OSS_CONTINUATION_TOKEN] = $result->getNextContinuationToken(); }else{ $bool = false; } } printf($prefix.":" . ($size / 1024) . "KB".PHP_EOL); -
Valor de retorno
A resposta a seguir é retornada ao chamar os métodos acima para obter os tamanhos dos objetos.
object namefun/movie/001.avi:0.01953125KB object namefun/movie/007.avi:290.71875KB object namefun/test.jpg:144.216796875KB fun/:434.955078125KB
Referências
Para ver o código de exemplo completo sobre como listar objetos, consulte o Exemplo no GitHub.
Para mais informações sobre as operações de API disponíveis para listar objetos, consulte GetBucket (ListObjects) e ListObjectsV2 (GetBucketV2).