Utilice la descarga en streaming para procesar el contenido de forma incremental cuando un archivo es muy grande o una descarga única tarda demasiado.
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 ubicados 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.
Este tema 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 utilizar la descarga en streaming, debe contar con el permiso
oss:GetObject. Para obtener más información, consulte Grant a custom policy.
Descargar un objeto a un stream
A continuación se muestra el código que descarga un objeto a un 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))
}
Descargar un objeto a un búfer
El siguiente código descarga un objeto a un búfer:
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())
}
Descargar un objeto a un archivo local
El código que se presenta a continuación descarga un objeto a un archivo 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)
}
Referencias
Código de ejemplo completo de descarga en streaming: Ejemplo en GitHub.
Referencia de la API de descarga en streaming: GetObject.