Todos os produtos
Search
Central de documentação

Object Storage Service:List objects (PHP SDK V1)

Última atualização: Sep 22, 2026

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).

Notas de uso

  • Neste tópico, utilizamos 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 suportados, 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 o uso de um domínio personalizado ou a autenticação com credenciais do Security Token Service (STS), consulte Criar um OssClient.

  • Para listar objetos, você deve ter 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. A operação não lista subdiretórios nem os objetos dentro deles.

  • Usar o 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. A operação não lista subdiretórios nem os objetos dentro deles. Por padrão, a operação retorna 100 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\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;
    }
    
  • Usar o método listObjectsV2

    O código a seguir mostra como usar o 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, a operação retorna até 100 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\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

Chame o método listObjects ou listObjectsV2 para listar um número especificado de objetos em um bucket.

  • Usar o método listObjects

    O código a seguir mostra como chamar 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");
      }
    }
  • Usar o método listObjectsV2

    O código a seguir mostra 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 com um prefixo especificado em um bucket.

  • Usar o método listObjects

    O código a seguir mostra como chamar o método listObjects para listar objetos com o prefixo dir 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 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");
      }
    }
  • Usar o método listObjectsV2

    O código a seguir mostra como chamar o método listObjectsV2 para listar objetos com o prefixo dir 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 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 vêm em ordem alfabética após um nome de objeto especificado.

  • Usar o método listObjects

    O código a seguir mostra como chamar o método listObjects para listar objetos que vêm em ordem alfabética após test.txt 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 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");
      }
    }
  • Usar o método listObjectsV2

    O código a seguir mostra como chamar o método listObjectsV2 para listar objetos que vêm em ordem alfabética após test.txt 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 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

Chame o método listObjects ou listObjectsV2 para listar todos os objetos de forma paginada. Especifique o número de objetos a serem retornados em cada página por meio do parâmetro maxKeys.

  • Usar o 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 de forma 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');
  • Usar o método listObjectsV2

    O código a seguir mostra como chamar o método listObjectsV2 para listar todos os objetos em um bucket chamado examplebucket de forma 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->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

Chame o método listObjects ou listObjectsV2 para listar objetos com um prefixo especificado de forma paginada.

  • Usar o método listObjects

    O código a seguir mostra como chamar o método listObjects para listar objetos com o prefixo dir em um bucket chamado examplebucket de forma 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);
    // 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');
  • Usar o método listObjectsV2

    O código a seguir mostra como chamar o método listObjectsV2 para listar objetos com o prefixo dir em um bucket chamado examplebucket de forma 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);
    // 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

Se o nome de um objeto contiver caracteres especiais, codifique o nome do objeto para transmissão. O OSS suporta apenas a codificação URL.

  • Aspas simples (')

  • Aspas duplas (")

  • E comercial (&)

  • Sinais de maior e menor (< >)

  • Vírgulas de enumeração (、)

  • Caracteres chineses

Chame o método listObjects ou listObjectsV2 e especifique a codificação dos nomes dos objetos.

  • Usar o método listObjects

    O código a seguir mostra como chamar o método listObjects e 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->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');
  • Usar o método listObjectsV2

    O código a seguir mostra como chamar o método listObjectsV2 e 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 e armazena todos os dados como objetos. Para simular um diretório, crie um objeto de 0 byte cujo nome termine com uma barra (/). Envie e baixe este objeto. O console do OSS exibe objetos cujos nomes terminam com uma barra (/) como diretórios.

Especifique 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, a operação lista os objetos e subdiretórios cujos nomes contêm o prefixo.

  • Ao especificar um prefixo e definir delimiter como uma barra (/) na solicitação, a operação lista os objetos e subdiretórios cujos nomes começam com o prefixo especificado no diretório. Cada subdiretório aparece como um único elemento de resultado em CommonPrefixes. A operação não lista os objetos e diretórios dentro desses subdiretórios.

Por exemplo, um bucket contém os seguintes objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi e fun/movie/007.avi. O exemplo define a barra (/) como o 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.

  • Usar o 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");
      }
    }
  • Usar o método listObjectsV2

    O código a seguir mostra 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

    Ao chamar os métodos anteriores para listar todos os objetos no bucket examplebucket, a API retorna a seguinte resposta.

    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/.

  • Usar o 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");
      }
    }
  • Usar o método listObjectsV2

    O código a seguir mostra 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

    Ao chamar os métodos anteriores para listar todos os objetos no diretório fun/, a API retorna a seguinte resposta.

    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/.

  • Usar o 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");
      }
    }
  • Usar o método listObjectsV2

    O código a seguir mostra 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 retornado

    Ao chamar os métodos anteriores para listar objetos e subdiretórios no diretório fun/, a API retorna a seguinte resposta.

    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/.

  • Usar o 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);
  • Usar o método listObjectsV2

    O código a seguir mostra 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 retornado

    Ao chamar os métodos anteriores para obter os tamanhos dos objetos, a API retorna a seguinte resposta.

    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