Use o download por streaming para processar 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 outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste exemplo, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
Este exemplo demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).
Para usar o download por streaming, você precisa da permissão
oss:GetObject. Para mais detalhes, consulte Conceder uma política personalizada.
Baixe 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))
}
Baixe 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())
}
Baixe 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 de download por streaming: Exemplo no GitHub.
Referência da API de download por streaming: GetObject.