All Products
Search
Document Center

Object Storage Service:List objects

Last Updated:Sep 11, 2023

This topic describes how to list objects in a versioning-enabled bucket, such as listing all objects, objects whose names contain a specified prefix, and objects and subdirectories in a specified directory.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

  • To list objects, you must have oss:ListObjectVersions permission. For more information, see Common examples of RAM policies.

Scenarios

The following figure shows the directories and objects in a bucket named examplebucket.

examplebucket
  └── fun
       └── exampleobject.jpg
       └── examplefile.txt
       └── destfolder
               └── image1.jpg
               └── image2.png
  └── srcfile.txt
  └── oss.jpg 

The following sections describe how to list different objects by specifying conditions.

For more information about the parameters that you can configure when you list objects, see ListObjectVersions (GetBucketVersions).

List the versions of all objects in a bucket

The following code provides an example on how to list the versions of all objects including delete markers in a specified bucket:

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
    // 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, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Specify the name of the bucket. 
    bucketName := "examplebucket"
    bucket,err := client.Bucket(bucketName)
    if err != nil {
        HandleError(err)
    }

    // List the versions of all objects including delete markers in the bucket. 
    keyMarker := oss.KeyMarker("")
    // The VersionIdMarker parameter is configured together with the KeyMarker parameter to specify the position from which the list operation starts. 
    versionIdMarker := oss.VersionIdMarker("")
    for {
        lor, err := bucket.ListObjectVersions(keyMarker,versionIdMarker)
        if err != nil {
            HandleError(err)
        }

        // Display the version IDs of the objects. 
        for _, dirName := range lor.ObjectVersions{
            fmt.Println("Versionid:",dirName.VersionId)
            fmt.Println("Key:",dirName.Key)
            fmt.Println("Is Latest",dirName.IsLatest)
        }
        // View the versions of the listed delete markers. 
         for _, marker  := range lor.ObjectDeleteMarkers {
            fmt.Println(marker.VersionId)
            fmt.Println(marker.Key)
        }
        // Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
        keyMarker = oss.KeyMarker(lor.NextKeyMarker)
        versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
        if !lor.IsTruncated {
            break
        }
    }
}

For more information about endpoints, see Regions and endpoints. For more information about bucket naming conventions, see Bucket.

Sample response:

Versionid: CAEQChiBgIDHzNPEthciIDYzZGQ5M2VjOTU2ODRmMzA4ZWM4ODk0NjVmMWEx****
Key: fun/
Is Latest true
Versionid: CAEQChiBgID61tnEthciIDNmOGM2MTQ3ZjU1NTQ2MGFhYWJjNjQxMTQxZWZh****
Key: fun/destfolder/
Is Latest true
Versionid: CAEQChiBgMDczt3EthciIDEwYjliZmQ4MDNiMDQ2Njk4YWMxM2NhM2E5NzQ3****
Key: fun/destfolder/image1.jpg
Is Latest true
Versionid: CAEQChiBgIDszt3EthciIGU5OWU0ZTllMGY3NTRmMmU5NzVjZmJkYmE3ZWYy****
Key: fun/destfolder/image2.png
Is Latest true
Versionid: CAEQChiBgICditzEthciIDBiNTg1ZTZkMDRlMzRjNDdiMjRjMTBlOGUzMTM0****
Key: fun/examplefile.txt
Is Latest true
Versionid: CAEQChiBgMC.itzEthciIDEzNWVlYjNhYzNmMjQ4NWM5Nzc2NzllY2FiYmQ3****
Key: fun/exampleobject.jpg
Is Latest true
Versionid: CAEQChiBgIDMgdbEthciIDUyMGI0NmZlNThkODQwY2ZhNmZhNTQ1Njk4ZTdj****
Key: oss.jpg
Is Latest true
Versionid: CAEQChiBgICIgdbEthciIDdlM2Q1YjYxZDIyZDQyMzI4MTRkNzVmYzdiMTBh****
Key: srcfile.txt
Is Latest true

List the versions of objects whose names contain a specified prefix

The following code provides an example on how to list the versions of objects whose names contain a specified prefix:

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
	// 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, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

    // Specify the name of the bucket. 
    bucketName := "examplebucket"
    bucket,err := client.Bucket(bucketName)
    if err != nil {
        HandleError(err)
    }

    // Specify the Prefix parameter to list the versions of objects whose names contain the fun prefix. 
    prefix := oss.Prefix("fun")
    keyMarker := oss.KeyMarker("")
    versionIdMarker := oss.VersionIdMarker("")
    for {
        lor, err := bucket.ListObjectVersions(prefix,keyMarker,versionIdMarker)
        if err != nil {
            HandleError(err)
        }

        // Display the version IDs of the objects. 
        for _, dirName := range lor.ObjectVersions{
            fmt.Println("Versionid:",dirName.VersionId)
            fmt.Println("Key:",dirName.Key)
            fmt.Println("Is Latest",dirName.IsLatest)
        }
        // Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
        keyMarker = oss.KeyMarker(lor.NextKeyMarker)
        versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
        if !lor.IsTruncated {
            break
        }
    }
}

Sample response:

Versionid: CAEQChiBgIDHzNPEthciIDYzZGQ5M2VjOTU2ODRmMzA4ZWM4ODk0NjVmMWEx****
Key: fun/
Is Latest true
Versionid: CAEQChiBgID61tnEthciIDNmOGM2MTQ3ZjU1NTQ2MGFhYWJjNjQxMTQxZWZh****
Key: fun/destfolder/
Is Latest true
Versionid: CAEQChiBgMDczt3EthciIDEwYjliZmQ4MDNiMDQ2Njk4YWMxM2NhM2E5NzQ3****
Key: fun/destfolder/image1.jpg
Is Latest true
Versionid: CAEQChiBgIDszt3EthciIGU5OWU0ZTllMGY3NTRmMmU5NzVjZmJkYmE3ZWYy****
Key: fun/destfolder/image2.png
Is Latest true
Versionid: CAEQChiBgICditzEthciIDBiNTg1ZTZkMDRlMzRjNDdiMjRjMTBlOGUzMTM0****
Key: fun/examplefile.txt
Is Latest true
Versionid: CAEQChiBgMC.itzEthciIDEzNWVlYjNhYzNmMjQ4NWM5Nzc2NzllY2FiYmQ3****
Key: fun/exampleobject.jpg
Is Latest true

List the versions of a specified number of objects

The following code provides an example on how to list the versions of a specified number of objects:

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
	// 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, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

    // Specify the name of the bucket. 
    bucketName := "examplebucket"
    bucket,err := client.Bucket(bucketName)
    if err != nil {
        HandleError(err)
    }

    // Specify the MaxKeys parameter to list up to four object versions in alphabetical order of the object names. 
    maxkey := oss.MaxKeys(4)
    keyMarker := oss.KeyMarker("")
    versionIdMarker := oss.VersionIdMarker("")
    for {
        lor, err := bucket.ListObjectVersions(maxkey,keyMarker,versionIdMarker)
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }

        // Display the version IDs of the objects. 
        for _, dirName := range lor.ObjectVersions{
            fmt.Println("Versionid:",dirName.VersionId)
            fmt.Println("Key:",dirName.Key)
            fmt.Println("Is Latest",dirName.IsLatest)
        }
        // Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
        keyMarker = oss.KeyMarker(lor.NextKeyMarker)
        versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
        if !lor.IsTruncated {
            break
        }
    }
}

Sample response:

Versionid: CAEQChiBgIDHzNPEthciIDYzZGQ5M2VjOTU2ODRmMzA4ZWM4ODk0NjVmMWEx****
Key: fun/
Is Latest true
Versionid: CAEQChiBgID61tnEthciIDNmOGM2MTQ3ZjU1NTQ2MGFhYWJjNjQxMTQxZWZh****
Key: fun/destfolder/
Is Latest true
Versionid: CAEQChiBgMDczt3EthciIDEwYjliZmQ4MDNiMDQ2Njk4YWMxM2NhM2E5NzQ3****
Key: fun/destfolder/image1.jpg
Is Latest true
Versionid: CAEQChiBgIDszt3EthciIGU5OWU0ZTllMGY3NTRmMmU5NzVjZmJkYmE3ZWYy****
Key: fun/destfolder/image2.png
Is Latest true

List the versions of all objects by page

The following code provides an example on how to list the versions of all objects by page:

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
	// 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, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

    // Specify the name of the bucket. 
    bucketName := "examplebucket"
    bucket,err := client.Bucket(bucketName)
    if err != nil {
        HandleError(err)
    }

    // List the versions of all objects in the bucket by page. 
    keyMarker := oss.KeyMarker("")
    // Specify the MaxKeys parameter to list up to four object versions in alphabetical order of the object names. 
    maxkey := oss.MaxKeys(4)
    versionIdMarker := oss.VersionIdMarker("")
    for {
        lor, err := bucket.ListObjectVersions(maxkey,keyMarker,versionIdMarker)
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }

        // Display the version IDs of the objects. 
        for _, dirName := range lor.ObjectVersions{
            fmt.Println("Versionid:",dirName.VersionId)
            fmt.Println("Key:",dirName.Key)
            fmt.Println("Is Latest",dirName.IsLatest)
        }

        fmt.Println("---------------")

        // Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
        if lor.IsTruncated {
            keyMarker = oss.KeyMarker(lor.NextKeyMarker)
            versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
        }else{
            break
        }
    }
}

Sample response:

Versionid: CAEQChiBgIDHzNPEthciIDYzZGQ5M2VjOTU2ODRmMzA4ZWM4ODk0NjVmMWEx****
Key: fun/
Is Latest true
Versionid: CAEQChiBgID61tnEthciIDNmOGM2MTQ3ZjU1NTQ2MGFhYWJjNjQxMTQxZWZh****
Key: fun/destfolder/
Is Latest true
Versionid: CAEQChiBgMDczt3EthciIDEwYjliZmQ4MDNiMDQ2Njk4YWMxM2NhM2E5NzQ3****
Key: fun/destfolder/image1.jpg
Is Latest true
Versionid: CAEQChiBgIDszt3EthciIGU5OWU0ZTllMGY3NTRmMmU5NzVjZmJkYmE3ZWYy****
Key: fun/destfolder/image2.png
Is Latest true
---------------
Versionid: CAEQChiBgICditzEthciIDBiNTg1ZTZkMDRlMzRjNDdiMjRjMTBlOGUzMTM0****
Key: fun/examplefile.txt
Is Latest true
Versionid: CAEQChiBgMC.itzEthciIDEzNWVlYjNhYzNmMjQ4NWM5Nzc2NzllY2FiYmQ3****
Key: fun/exampleobject.jpg
Is Latest true
Versionid: CAEQChiBgIDMgdbEthciIDUyMGI0NmZlNThkODQwY2ZhNmZhNTQ1Njk4ZTdj****
Key: oss.jpg
Is Latest true
Versionid: CAEQChiBgICIgdbEthciIDdlM2Q1YjYxZDIyZDQyMzI4MTRkNzVmYzdiMTBh****
Key: srcfile.txt
Is Latest true
---------------

List objects in a directory

OSS uses a flat structure to store objects. A directory is a zero-byte object whose name ends with a forward slash (/). You can upload and download a directory. By default, an object whose name ends with a forward slash (/) is displayed as a directory in the OSS console.

You can specify the delimiter and prefix parameters in the request to list objects by directory.

  • If you set prefix to a directory name in the request, objects and subdirectories whose names contain the prefix are listed.

  • If you specify a prefix and set delimiter to a forward slash (/) in the request, objects and subdirectories whose names start with the specified prefix in the directory are listed. Each subdirectory is listed as a single result element in CommonPrefixes. The objects and directories in these subdirectories are not listed.

The following examples describe how to list objects in simulated directories.

  • List the versions of objects within the root directory of a bucket

    The following code provides an example on how to list the versions of objects in the root directory of a bucket:

    package main
    
    import (
        "fmt"
        "os"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func HandleError(err error) {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    
    func main() {
    	// 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, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Create an OSSClient instance. 
    	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
        // Specify the name of the bucket. 
        bucketName := "examplebucket"
        bucket,err := client.Bucket(bucketName)
        if err != nil {
            HandleError(err)
        }
    
        // Set the delimiter parameter to a forward slash (/) to list the versions of objects and the names of subdirectories in the root directory. 
        delimiter := oss.Delimiter("/")
        keyMarker := oss.KeyMarker("")
        versionIdMarker := oss.VersionIdMarker("")
        for {
            lor, err := bucket.ListObjectVersions(keyMarker,delimiter,versionIdMarker)
            if err != nil {
                HandleError(err)
            }
    
            // Display the version IDs of the objects. 
            for _, dirName := range lor.ObjectVersions{
                fmt.Println("Versionid:",dirName.VersionId)
                fmt.Println("Key:",dirName.Key)
                fmt.Println("Is Latest",dirName.IsLatest)
            }
    
            // Display the directories whose names end with a forward slash (/). 
            for _,common_prefix := range lor.CommonPrefixes{
                fmt.Println("common_prefix:",common_prefix)
            }
            // Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
            if lor.IsTruncated {
                keyMarker = oss.KeyMarker(lor.NextKeyMarker)
                versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
            }else{
                break
            }
        }
    }

    Sample response:

    Versionid: CAEQChiBgIDMgdbEthciIDUyMGI0NmZlNThkODQwY2ZhNmZhNTQ1Njk4ZTdj****
    Key: oss.jpg
    Is Latest true
    Versionid: CAEQChiBgICIgdbEthciIDdlM2Q1YjYxZDIyZDQyMzI4MTRkNzVmYzdiMTBh****
    Key: srcfile.txt
    Is Latest true
    common_prefix: fun/
  • List objects and subdirectories in a directory

    The following code provides an example on how to list the objects and the subdirectories in a directory of a bucket:

    package main
    
    import (
        "fmt"
        "os"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func HandleError(err error) {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    
    func main() {
    	// 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, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Create an OSSClient instance. 
    	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
        // Specify the name of the bucket. 
        bucketName := "examplebucket"
        bucket,err := client.Bucket(bucketName)
        if err != nil {
            HandleError(err)
        }
    
        // Configure the Prefix parameter to list all objects and subdirectories in the fun directory. Set the delimiter parameter to a forward slash (/). 
        prefix := oss.Prefix("fun/")
        delimiter := oss.Delimiter("/")
        keyMarker := oss.KeyMarker("")
        versionIdMarker := oss.VersionIdMarker("")
        for {
            lor, err := bucket.ListObjectVersions(prefix,delimiter,keyMarker,versionIdMarker)
            if err != nil {
                HandleError(err)
            }
    
            // Display the version IDs of the objects. 
            for _, dirName := range lor.ObjectVersions{
                fmt.Println("Versionid:",dirName.VersionId)
                fmt.Println("Key:",dirName.Key)
                fmt.Println("Is Latest:",dirName.IsLatest)
            }
    
            // Display the directories whose names end with a forward slash (/). 
            for _,common_prefix := range lor.CommonPrefixes{
                fmt.Println("common_prefix:",common_prefix)
            }
            // Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
            if lor.IsTruncated {
                keyMarker = oss.KeyMarker(lor.NextKeyMarker)
                versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
            }else{
                break
            }
        }
    }

    Sample response:

    Versionid: CAEQChiBgIDHzNPEthciIDYzZGQ5M2VjOTU2ODRmMzA4ZWM4ODk0NjVmMWEx****
    Key: fun/
    Is Latest: true
    Versionid: CAEQChiBgICditzEthciIDBiNTg1ZTZkMDRlMzRjNDdiMjRjMTBlOGUzMTM0****
    Key: fun/examplefile.txt
    Is Latest: true
    Versionid: CAEQChiBgMC.itzEthciIDEzNWVlYjNhYzNmMjQ4NWM5Nzc2NzllY2FiYmQ3****
    Key: fun/exampleobject.jpg
    Is Latest: true
    common_prefix: fun/destfolder/