Descargue objetos de un bucket de OSS a un dispositivo local mediante el método GetObject o GetObjectToFile.
Notas de uso
El código de ejemplo utiliza el ID de región
cn-hangzhou(China (Hangzhou)) y el endpoint público. Para acceder al bucket desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.Las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.
Permisos
De forma predeterminada, una cuenta de Alibaba Cloud tiene permisos completos. Los usuarios de RAM o los roles de RAM bajo una cuenta de Alibaba Cloud no tienen ningún permiso por defecto. La cuenta de Alibaba Cloud o el administrador de la cuenta debe otorgar los permisos de operación mediante RAM policies o Bucket Policy.
|
API |
Acción |
Descripción |
|
GetObject |
|
Descarga un objeto. |
|
|
Este permiso es obligatorio si especifica la versión del objeto mediante versionId al descargarlo. |
|
|
|
Este permiso es obligatorio si los metadatos del objeto contienen X-Oss-Server-Side-Encryption: KMS durante la descarga. |
Método
func (c *Client) GetObject(ctx context.Context, request *GetObjectRequest, optFns ...func(*Options)) (*GetObjectResult, error)
Parámetros de solicitud
|
Parámetro |
Tipo |
Descripción |
|
ctx |
context.Context |
Contexto de la solicitud. Utilícelo para establecer el tiempo de espera total de la solicitud. |
|
request |
*GetObjectRequest |
Parámetros de la solicitud. GetObjectRequest. |
|
optFns |
...func(*Options) |
Opcional. Anulaciones de parámetros a nivel de operación. Options. |
Parámetros de respuesta
|
Parámetro |
Tipo |
Descripción |
|
result |
*GetObjectResult |
Respuesta de la operación. Disponible cuando err es nil. GetObjectResult. |
|
err |
error |
El error. No es nil si la solicitud falla. |
Código de ejemplo
Descargue un objeto de un bucket a un archivo local:
package main
import (
"context"
"flag"
"io"
"log"
"os"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define the global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Use the init function to initialize parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Define the path of the output file.
outputFile := "downloaded.file" // Replace the string with the path of the output file.
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to query the object.
request := &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
}
// Query the object and process the results.
result, err := client.GetObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to get object %v", err)
}
defer result.Body.Close() // Close the response body when the function is complete.
// Read all data within the object.
data, err := io.ReadAll(result.Body)
if err != nil {
log.Fatalf("failed to read object %v", err)
}
// Write the data to a file.
err = os.WriteFile(outputFile, data, 0644)
if err != nil {
log.Fatalf("failed to write to output file %v", err)
}
log.Printf("file downloaded successfully to %s", outputFile)
}
Escenarios comunes
Descarga condicional
Monitoreo del progreso de descarga
Descarga por lotes de objetos a un dispositivo local
Referencias
Código de ejemplo completo: GitHub.
Referencia de API: GetObjectToFile y GetObject.