Todos los productos
Search
Centro de documentos

Object Storage Service:List objects (Go SDK V1)

Última actualización: Sep 24, 2026

Este tema describe cómo listar todos los objetos, los objetos con un prefijo específico y los objetos junto con sus subdirectorios dentro de un directorio determinado en un bucket de Object Storage Service (OSS).

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud que estén en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Las credenciales de acceso se obtienen de variables de entorno. Para conocer cómo configurar estas credenciales, consulte Configure access credentials.

  • Aquí se muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para listar objetos, debe contar con el permiso oss:ListObjects. Para obtener más información, consulte Grant a custom policy.

  • OSS SDK for Go 2.2.5 y versiones posteriores admiten devolver información de RestoreInfo.

Contexto

Puede llamar a la operación ListObjectsV2 o ListObjects para listar hasta 1,000 objetos de un bucket por cada llamada. Al especificar distintos parámetros, es posible implementar diversas funciones de listado. Por ejemplo, puede listar todos los objetos a partir de una posición inicial, enumerar objetos y subdirectorios de un directorio específico o paginar los resultados. Las principales diferencias entre ambas operaciones son las siguientes:

  • Cuando utiliza la operación ListObjectsV2 , debe usar el parámetro fetchOwner para indicar si los resultados incluirán la información Owner de los objetos.

  • Si emplea la operación ListObjects , la información Owner de los objetos se incluye de forma predeterminada en los resultados.

    Nota

    En los buckets con control de versiones habilitado, debe utilizar la operación ListObjectsV2 para listar los objetos.

A continuación se describen los parámetros para listar objetos mediante los métodos ListObjectsV2 y ListObjects.

ListObjectsV2

La siguiente tabla describe los parámetros para listar objetos con el método ListObjectsV2.

Parámetro

Descripción

prefix

Prefijo que deben contener los nombres de los objetos devueltos.

delimiter

Carácter utilizado para agrupar nombres de objetos. Todos los nombres que comparten la misma cadena, desde el prefijo hasta la primera aparición del delimitador, se agrupan como un solo elemento (commonPrefixes).

startAfter

Punto de inicio de esta operación de listado.

fetchOwner

Indica si los resultados incluyen la información Owner.

  • true: la información Owner se incluye en los resultados.

  • false: la información Owner no se incluye en los resultados.

Para obtener más información, consulte ListObjectsV2.

ListObjects

La siguiente tabla describe los parámetros para listar objetos con el método ListObjects.

Parámetro

Descripción

delimiter

Carácter utilizado para agrupar nombres de objetos. Todos los nombres que comparten la misma cadena, desde el prefijo hasta la primera aparición del delimitador, se agrupan como un solo elemento (commonPrefixes).

prefix

Prefijo que deben contener los nombres de los objetos devueltos.

maxKeys

Número máximo de objetos que se devuelven. El valor predeterminado es 100 y el máximo es 1000.

marker

Punto de inicio de esta operación de listado.

Para obtener más información, consulte ListObjects.

Ejemplos

ListObjectsV2

El siguiente código de ejemplo muestra cómo usar el método ListObjectsV2 para listar 100 objetos de un bucket.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// The initial continuation token.
	continueToken := ""

	for {
		// List all objects.
		lsRes, err := bucket.ListObjectsV2(oss.ContinuationToken(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		for _, object := range lsRes.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
		}

		// If more objects need to be listed, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

El siguiente código de ejemplo muestra cómo usar el método ListObjects para listar 100 objetos de un bucket.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List all objects.
	marker := ""
	for {
		lsRes, err := bucket.ListObjects(oss.Marker(marker))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		for _, object := range lsRes.Objects {
			log.Printf("Object Name: %s\n", object.Key)
		}

		// If more objects need to be listed, update the marker and continue the loop.
		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Escenarios comunes

Listar una cantidad específica de objetos

ListObjectsV2

A continuación se muestra un ejemplo de código que utiliza el método ListObjectsV2 para listar una cantidad específica de objetos.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Set MaxKeys to specify the maximum number of objects to list, and then list the objects.
	maxKeys := 200
	continueToken := ""

	for {
		lsRes, err := bucket.ListObjectsV2(oss.MaxKeys(maxKeys), oss.StartAfter(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		for _, object := range lsRes.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s, Owner ID: %s, Owner DisplayName: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass, object.Owner.ID, object.Owner.DisplayName)
		}

		// If more objects need to be listed, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.ContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

A continuación se muestra un ejemplo de código que utiliza el método ListObjects para listar una cantidad específica de objetos.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Set the maximum number of objects to list, and then list the objects.
	maxKeys := 200
	lsRes, err := bucket.ListObjects(oss.MaxKeys(maxKeys))
	if err != nil {
		log.Fatalf("Failed to list objects: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	log.Printf("Found %d objects:\n", len(lsRes.Objects))
	for _, object := range lsRes.Objects {
		log.Printf("Object: %s\n", object.Key)
	}

	if lsRes.IsTruncated {
		log.Printf("More objects available. NextMarker: %s\n", lsRes.NextMarker)
	} else {
		log.Println("All objects have been listed.")
	}
}

Listar objetos con un prefijo específico

ListObjectsV2

A continuación se muestra un ejemplo de código que utiliza el método ListObjectsV2 para listar objetos con un prefijo específico.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Set the Prefix parameter to list objects whose names start with my-object-.
	prefix := "my-object-"
	lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix))
	if err != nil {
		log.Fatalf("Failed to list objects: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
	for _, object := range lsRes.Objects {
		log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s, Owner ID: %s, Owner DisplayName: %s\n",
			object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass, object.Owner.ID, object.Owner.DisplayName)
	}

	if lsRes.IsTruncated {
		log.Printf("More objects available. Next Continuation Token: %s\n", lsRes.NextContinuationToken)
	} else {
		log.Println("All objects have been listed.")
	}
}

ListObjects

A continuación se muestra un ejemplo de código que utiliza el método ListObjects para listar objetos con un prefijo específico.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List objects with the specified prefix. By default, 100 objects are listed.
	prefix := "my-object-"
	lsRes, err := bucket.ListObjects(oss.Prefix(prefix))
	if err != nil {
		log.Fatalf("Failed to list objects: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
	for _, object := range lsRes.Objects {
		log.Printf("Object Key: %s\n", object.Key)
	}

	if lsRes.IsTruncated {
		log.Printf("More objects available. Next Marker: %s\n", lsRes.NextMarker)
	} else {
		log.Println("All objects have been listed.")
	}
}

Listar objetos a partir de un punto de inicio especificado

ListObjectsV2

Establezca el parámetro StartAfter para indicar el punto de inicio del listado. Se devuelven todos los objetos que, en orden lexicográfico, aparecen después del valor de StartAfter.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Specify to list objects after StartAfter. By default, 100 objects are listed.
	startAfter := "my-object-"
	lsRes, err := bucket.ListObjectsV2(oss.StartAfter(startAfter))
	if err != nil {
		log.Fatalf("Failed to list objects: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	log.Printf("Found %d objects starting after '%s':\n", len(lsRes.Objects), startAfter)
	for _, object := range lsRes.Objects {
		log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s, Owner ID: %s, Owner DisplayName: %s\n",
			object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass, object.Owner.ID, object.Owner.DisplayName)
	}

	if lsRes.IsTruncated {
		log.Printf("More objects available. Next Continuation Token: %s\n", lsRes.NextContinuationToken)
	} else {
		log.Println("All objects have been listed.")
	}
}

ListObjects

Establezca el parámetro Marker para indicar el punto de inicio del listado. Se devuelven todos los objetos que, en orden lexicográfico, aparecen después del valor de Marker.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Initialize the marker.
	marker := ""

	// Loop to list all objects.
	for {
		lsRes, err := bucket.ListObjects(oss.Marker(marker))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects:\n", len(lsRes.Objects))
		for _, object := range lsRes.Objects {
			log.Printf("Object: %s\n", object.Key)
		}

		// If the result is truncated, update the marker and continue the loop.
		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Listar todos los objetos por página

ListObjectsV2

Utilice el método ListObjectsV2 para listar por página todos los objetos de un bucket. Establezca MaxKeys para indicar la cantidad de objetos que se mostrarán en cada página.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List all objects by page. List 100 objects per page.
	continueToken := ""
	for {
		lsRes, err := bucket.ListObjectsV2(oss.MaxKeys(100), oss.ContinuationToken(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects:\n", len(lsRes.Objects))
		for _, object := range lsRes.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
		}

		// If the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

Utilice el método ListObjects para listar por página todos los objetos de un bucket. Establezca MaxKeys para indicar la cantidad de objetos que se mostrarán en cada página.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List all objects by page. List 100 objects per page.
	marker := ""
	for {
		lsRes, err := bucket.ListObjects(oss.MaxKeys(100), oss.Marker(marker))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects:\n", len(lsRes.Objects))
		for _, object := range lsRes.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
		}

		// If the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Listar objetos con un prefijo específico por página

ListObjectsV2

Utilice el método ListObjectsV2 para listar por página los objetos con un prefijo específico. Establezca MaxKeys para indicar la cantidad de objetos que se mostrarán en cada página.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List objects with a specific prefix by page. List 80 objects per page.
	prefix := "my-object-"
	continueToken := ""
	for {
		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.MaxKeys(80), oss.ContinuationToken(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
		for _, object := range lsRes.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
		}

		// If the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

Utilice el método ListObjects para listar por página los objetos con un prefijo específico. Establezca MaxKeys para indicar la cantidad de objetos que se mostrarán en cada página.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List objects with the specified prefix by page. List 80 objects per page.
	prefix := "my-object-"
	marker := ""
	for {
		lsRes, err := bucket.ListObjects(oss.MaxKeys(80), oss.Marker(marker), oss.Prefix(prefix))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
		for _, object := range lsRes.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
		}

		// If the result is truncated, update the marker and continue the loop.
		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Listar la información de todos los objetos en un directorio específico

ListObjectsV2

Utilice el método ListObjectsV2 para listar la información de todos los objetos en un directorio específico (prefijo). Esta información incluye el tamaño del objeto, la fecha de última modificación y el nombre.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List objects with the specified prefix by page. By default, 100 records are returned at a time.
	continueToken := ""
	prefix := "fun"
	for {
		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results.
		for _, object := range lsRes.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
		}

		// If the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

Utilice el método ListObjects para listar la información de todos los objetos en un directorio específico (prefijo). Esta información incluye el tamaño del objeto, la fecha de última modificación y el nombre.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Traverse the objects.
	marker := ""
	prefix := "test"
	for {
		lor, err := bucket.ListObjects(oss.Marker(marker), oss.Prefix(prefix))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results.
		for _, object := range lor.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass)
		}

		// If the result is truncated, update the marker and continue the loop.
		if lor.IsTruncated {
			marker = lor.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Listar la información de todos los subdirectorios en un directorio específico

ListObjectsV2

A continuación se muestra un ejemplo de código que utiliza el método ListObjectsV2 para listar la información de todos los subdirectorios en un directorio específico (prefijo).

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List folders with the specified prefix by page. By default, 100 records are returned at a time.
	continueToken := ""
	prefix := ""
	for {
		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken), oss.Delimiter("/"))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results.
		for _, dirName := range lsRes.CommonPrefixes {
			log.Println("Directory Name:", dirName)
		}

		// If the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All directories have been listed.")
}

ListObjects

A continuación se muestra un ejemplo de código que utiliza el método ListObjects para listar la información de todos los subdirectorios en un directorio específico (prefijo).

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List folders with the specified prefix by page. By default, 100 records are returned at a time.
	marker := ""
	prefix := "yourDirPrefix" // Replace with the actual prefix.
	for {
		lor, err := bucket.ListObjects(oss.Marker(marker), oss.Prefix(prefix), oss.Delimiter("/"))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results.
		for _, dirName := range lor.CommonPrefixes {
			log.Println("Directory Name:", dirName)
		}

		// If the result is truncated, update the continuation token and continue the loop.
		if lor.IsTruncated {
			marker = lor.NextMarker
		} else {
			break
		}
	}

	log.Println("All directories have been listed.")
}

Listar objetos y devolver la información de Owner

A continuación se muestra un ejemplo de código que utiliza el método ListObjectsV2 para listar objetos y devolver su información de Owner.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Obtain Owner information and list the objects.
	lsRes, err := bucket.ListObjectsV2(oss.FetchOwner(true))
	if err != nil {
		log.Fatalf("Failed to list objects with owner information: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	for _, object := range lsRes.Objects {
		log.Printf("Object Key: %s, Owner ID: %s, Display Name: %s\n",
			object.Key, object.Owner.ID, object.Owner.DisplayName)
	}

	log.Println("All objects have been listed.")
}

Carpetas

OSS utiliza una estructura plana para almacenar objetos. Un directorio es un objeto de cero bytes cuyo nombre termina con una barra diagonal (/). Este objeto se puede cargar y descargar. De forma predeterminada, un objeto cuyo nombre termina con una barra diagonal (/) se muestra como un directorio en la consola de OSS. Para consultar el código de ejemplo completo que se usa para crear directorios, visite GitHub.

Especifique los parámetros delimiter y prefix para listar objetos por directorio.

  • Si establece prefix con el nombre de un directorio en la solicitud, se listan los objetos y subdirectorios cuyos nombres contienen ese prefijo.

  • Si especifica un prefijo y establece delimiter con una barra diagonal (/) en la solicitud, se listan los objetos y subdirectorios del directorio cuyos nombres comienzan con dicho prefijo. Cada subdirectorio aparece como un único elemento de resultado en CommonPrefixes. Los objetos y directorios dentro de estos subdirectorios no se listan.

Por ejemplo, suponga que un bucket contiene los siguientes objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi y fun/movie/007.avi. La barra diagonal (/) se especifica como delimitador de directorios. A continuación se describe cómo listar objetos en directorios simulados.

  • Listar todos los objetos de un bucket

    • ListObjectsV2

      A continuación se muestra un ejemplo de código que utiliza ListObjectsV2 para listar todos los objetos de un bucket.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List all objects in the specified bucket.
      	startAfter := ""
      	continueToken := ""
      	for {
      		lsRes, err := bucket.ListObjectsV2(oss.StartAfter(startAfter), oss.ContinuationToken(continueToken))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			startAfter = lsRes.StartAfter
      			continueToken = lsRes.NextContinuationToken
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed.")
      }
      

      ListObjects

      A continuación se muestra un ejemplo de código que utiliza el método ListObjects para listar todos los objetos de un bucket.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List all objects in the specified bucket.
      	marker := ""
      	for {
      		lsRes, err := bucket.ListObjects(oss.Marker(marker))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			marker = lsRes.NextMarker
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed.")
      }
      
    • Al usar cualquiera de los dos métodos anteriores para listar todos los objetos del bucket, se devuelve el siguiente resultado.

      Objects:
      fun/movie/001.avi
      fun/movie/007.avi
      fun/test.jpg
      oss.jpg
      CommonPrefixes:  
  • Listar todos los objetos de un directorio específico

    • ListObjectsV2

      A continuación se muestra un ejemplo de código que utiliza el método ListObjectsV2 para listar todos los objetos de un directorio específico.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List all objects in the specified directory.
      	prefix := "aaa/db-init"
      	continueToken := ""
      	for {
      		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			continueToken = lsRes.NextContinuationToken
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed.")
      }
      

      ListObjects

      A continuación se muestra un ejemplo de código que utiliza el método ListObjects para listar todos los objetos de un directorio específico.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List all objects in the specified directory.
      	prefix := "aaa/db-init" // Replace with the actual prefix.
      	marker := ""
      	for {
      		lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			marker = lsRes.NextMarker
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed.")
      }
      
    • Al usar cualquiera de los dos métodos anteriores para listar todos los objetos del directorio especificado, se devuelve el siguiente resultado.

      Objects:
      fun/movie/001.avi
      fun/movie/007.avi
      fun/test.jpg
      CommonPrefixes: 
  • Listar objetos y subdirectorios de un directorio

    • ListObjectsV2

      A continuación se muestra un ejemplo de código que utiliza el método ListObjectsV2 para listar objetos y subdirectorios de un directorio.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List objects and subdirectories in the specified directory.
      	prefix := "" // Set a prefix as needed.
      	delimiter := "/"
      	continueToken := ""
      	for {
      		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.Delimiter(delimiter), oss.ContinuationToken(continueToken))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// Print the subdirectories.
      		for _, commonPrefix := range lsRes.CommonPrefixes {
      			log.Printf("Common Prefix: %s\n", commonPrefix)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			continueToken = lsRes.NextContinuationToken
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects and subdirectories have been listed.")
      }
      

      ListObjects

      A continuación se muestra un ejemplo de código que utiliza el método ListObjects para listar objetos y subdirectorios de un directorio.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List objects and subdirectories in the specified directory.
      	prefix := "aaa/db-init/" // Replace with the actual prefix.
      	marker := ""
      	delimiter := "/"
      	for {
      		lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker), oss.Delimiter(delimiter))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the list of objects.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// Print the list of subdirectories.
      		for _, commonPrefix := range lsRes.CommonPrefixes {
      			log.Printf("Common Prefix: %s\n", commonPrefix)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			marker = lsRes.NextMarker
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects and subdirectories have been listed.")
      }
      
    • Al usar cualquiera de los dos métodos anteriores para listar objetos y subdirectorios del directorio especificado, se devuelve el siguiente resultado.

      Objects:
      fun/test.jpg
      
      CommonPrefixes:
      fun/movie/   
  • Obtener el tamaño de los objetos en un directorio específico

    • ListObjectsV2

      A continuación se muestra un ejemplo de código que utiliza el método ListObjectsV2 para obtener el tamaño de los objetos en un directorio específico.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Get the bucket.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// Get the size of objects in the specified directory.
      	prefix := "/fun" // Replace with the actual prefix.
      	continueToken := ""
      	for {
      		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the list of objects and their sizes.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s, Size: %d Byte(s)\n", object.Key, object.Size)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			continueToken = lsRes.NextContinuationToken
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed with their sizes.")
      }
      

      ListObjects

      A continuación se muestra un ejemplo de código que utiliza el método ListObjects para obtener el tamaño de los objetos en un directorio específico.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// Get the size of objects in the specified directory.
      	prefix := "test/" // Replace with the actual prefix.
      	marker := ""
      	for {
      		lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the list of objects and their sizes.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s, Size: %d Byte(s)\n", object.Key, object.Size)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			marker = lsRes.NextMarker
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed with their sizes.")
      }
      

Preguntas frecuentes

¿Puedo ordenar los objetos por la fecha de última modificación al listarlos?

No. Para ordenar los objetos por la fecha de última modificación, utilice data indexing.

Referencias

  • Para consultar el código de ejemplo completo sobre cómo listar objetos, consulte el ejemplo en GitHub.

  • Para obtener más información sobre las operaciones de API que permiten listar objetos, consulte ListObjectsV2 y ListObjects.