Todos os produtos
Search
Central de documentação

Object Storage Service:Streaming download (Go SDK V1)

Última atualização: Sep 22, 2026

Use o download por streaming para processar o conteúdo de forma incremental quando o arquivo for grande ou quando um único download demorar muito.

Observações

  • Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outro serviço da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.

  • Este tópico usa credenciais de acesso obtidas de variáveis de ambiente. Para mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials.

  • Este tópico demonstra como criar uma instância do OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para usar o download por streaming, é necessária a permissão oss:GetObject. Para mais informações, consulte Grant a custom policy.

Download de um objeto para um stream

O código a seguir baixa um objeto para um stream:

package main

import (
	"io"
	"log"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure 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, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Set yourBucketName to the name of the bucket.
	bucket, err := client.Bucket("yourBucketName")
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Download the object to a stream.
	body, err := bucket.GetObject("yourObjectName")
	if err != nil {
		log.Fatalf("Failed to get object: %v", err)
	}
	// After the data is read, close the stream. Otherwise, a connection leak may occur. This can exhaust the connection pool and cause the program to stop working.
	defer body.Close()

	data, err := io.ReadAll(body)
	if err != nil {
		log.Fatalf("Failed to read all data from object: %v", err)
	}
	log.Println("Data:", string(data))
}

Download de um objeto para um buffer

O código a seguir baixa um objeto para um buffer:

package main

import (
	"bytes"
	"io"
	"log"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure 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, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

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

	// Download the object to a buffer.
	// Set yourObjectName to the full path of the object. The full path does not include the bucket name.
	objectName := "yourObjectName" // Replace this with the actual object path.
	body, err := bucket.GetObject(objectName)
	if err != nil {
		log.Fatalf("Failed to get object: %v", err)
	}
	defer body.Close()

	buf := new(bytes.Buffer)
	_, err = io.Copy(buf, body)
	if err != nil {
		log.Fatalf("Failed to copy object to buffer: %v", err)
	}

	log.Println("Buffer content:", buf.String())
}

Download de um objeto para um arquivo local

O código a seguir baixa um objeto para um arquivo local:

package main

import (
	"io"
	"log"
	"os"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure 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, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

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

	// Download the object to a local file.
	// Set yourObjectName to the full path of the object. The full path does not include the bucket name.
	objectName := "yourObjectName" // Replace this with the actual object path.
	body, err := bucket.GetObject(objectName)
	if err != nil {
		log.Fatalf("Failed to get object: %v", err)
	}
	defer body.Close()

	// Open or create a local file.
	localFilePath := "LocalFile" // Replace this with the actual local file path.
	fd, err := os.OpenFile(localFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
	if err != nil {
		log.Fatalf("Failed to open or create local file: %v", err)
	}
	defer fd.Close()

	// Copy the content of the OSS object to the local file.
	_, err = io.Copy(fd, body)
	if err != nil {
		log.Fatalf("Failed to copy object to local file: %v", err)
	}

	log.Println("File downloaded successfully to", localFilePath)
}

Referências

  • Código de exemplo completo para download por streaming: Exemplo no GitHub.

  • Referência da API para download por streaming: GetObject.