Todos los productos
Search
Centro de documentos

Object Storage Service:Descarga de objetos como archivos (OSS SDK for Go 1.0)

Última actualización: Sep 03, 2026

Este tema describe cómo descargar un objeto de un bucket a su computadora.

Notas de uso

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

  • En este tema, 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.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como el uso de un dominio personalizado o la autenticación con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para descargar un objeto como archivo local, debe contar con el permiso oss:GetObject. Para obtener más información, consulte Grant a custom policy.

Ejemplos

A continuación se presenta un código de ejemplo que muestra cómo descargar el objeto exampleobject.txt del directorio exampledir de un bucket llamado examplebucket a D:\localpath. Una vez descargado el objeto, el archivo local se nombra examplefile.txt.

package main

import (
	"log"

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

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

    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
    clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    clientOptions = append(clientOptions, oss.Region("yourRegion"))
    // Specify the version of the signature algorithm.
    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)
    }

    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket" // Replace examplebucket 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 the specified local path. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path. 
    // If you do not specify a local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
    // Specify the full path of the object that you want to download from the bucket. Example: exampledir/exampleobject.txt. Then, specify the full path of the local file in which you want to store the downloaded object. Example: D:\\localpath\\examplefile.txt. Do not include the bucket name in the full path. 
    objectName := "exampledir/exampleobject.txt"
    localFilePath := "D:\\localpath\\examplefile.txt"
    err = bucket.GetObjectToFile(objectName, localFilePath)
    if err != nil {
        log.Fatalf("Failed to download file: %v", err)
    }

    log.Println("File downloaded successfully.")
}

Escenarios comunes

Conditional download

Al descargar un solo objeto de un bucket, puede especificar condiciones basadas en la última hora de modificación o en el ETag del objeto. El objeto se descarga únicamente si se cumplen estas condiciones; de lo contrario, se devuelve un error y no se inicia la operación de descarga. Esto reduce la transmisión de red innecesaria y el consumo de recursos, además de mejorar la eficiencia de la descarga.

La siguiente tabla describe las condiciones disponibles que puede especificar.

Nota
  • If-Modified-Since e If-Unmodified-Since pueden usarse conjuntamente. Asimismo, If-Match e If-None-Match también pueden combinarse.

  • Obtenga el ETag mediante la llamada a ossClient.getObjectMetadata.

Condición

Descripción

Método

IfModifiedSince

Si la hora especificada es anterior a la última modificación del objeto, este se puede descargar. De lo contrario, se devuelve 304 Not Modified.

oss.IfModifiedSince

IfUnmodifiedSince

Si la hora especificada es posterior o igual a la última modificación del objeto, este se puede descargar. De lo contrario, se devuelve 412 Precondition Failed.

oss.IfUnmodifiedSince

IfMatch

Si el ETag especificado coincide con el del objeto, este se puede descargar. De lo contrario, se devuelve 412 Precondition Failed.

oss.IfMatch

IfNoneMatch

Si el ETag especificado no coincide con el del objeto, este se puede descargar. De lo contrario, se devuelve 304 Not Modified.

oss.IfNoneMatch

El siguiente código de ejemplo muestra cómo realizar una descarga condicional:

package main

import (
    "log"
    "time"
    
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

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

    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
    clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    clientOptions = append(clientOptions, oss.Region("yourRegion"))
    // Specify the version of the signature algorithm.
    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)
    }

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

    // For example, an object was last modified at 18:43:02, November 21, 2023. If the specified time is earlier than the last modified time, the object meets the If-Modified-Since condition and the object is downloaded. 
    date := time.Date(2023, time.November, 21, 18, 43, 2, 0, time.UTC)

    // Specify the full path of the object. Do not include the bucket name in the full path. 
    objectName := "yourObjectName" // Replace yourObjectName with the actual object name.
    localFilePath := "LocalFile" // Specify the full path of the local file in which you want to store the downloaded object.

    // The object is not downloaded if it does not meet the specified conditions. 
    err = bucket.GetObjectToFile(objectName, localFilePath, oss.IfUnmodifiedSince(date))
    if err == nil {
        log.Fatal("Expected an error when the condition is not met, but got nil")
    }

    // The object is downloaded if it meets the specified conditions. 
    err = bucket.GetObjectToFile(objectName, localFilePath, oss.IfModifiedSince(date))
    if err != nil {
        log.Fatalf("Failed to download file: %v", err)
    }

    log.Println("File has been downloaded successfully.")
}

Display of the download progress

Al descargar un objeto, puede usar la barra de progreso para consultar el avance de la descarga en tiempo real. Esto le permite comprobar si la tarea de descarga se ha detenido tras esperar un tiempo prolongado.

El siguiente código de ejemplo muestra cómo visualizar el progreso de descarga de un objeto llamado exampleobject.txt desde un bucket denominado examplebucket:

package main

import (
	"log"
	"sync/atomic"

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

// Specify the progress bar listener. 
type OssProgressListener struct {
	lastProgress int64
}

// Specify the function that is used to handle progress change events. 
func (listener *OssProgressListener) ProgressChanged(event *oss.ProgressEvent) {
	switch event.EventType {
	case oss.TransferStartedEvent:
		log.Printf("Transfer Started, ConsumedBytes: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	case oss.TransferDataEvent:
		if event.TotalBytes != 0 {
			progress := int64(event.ConsumedBytes * 100 / event.TotalBytes)
			if progress > atomic.LoadInt64(&listener.lastProgress) {
				atomic.StoreInt64(&listener.lastProgress, progress)
				log.Printf("\rTransfer Data, ConsumedBytes: %d, TotalBytes %d, %d%%.",
					event.ConsumedBytes, event.TotalBytes, progress)
			}
		}
	case oss.TransferCompletedEvent:
		log.Printf("\nTransfer Completed, ConsumedBytes: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	case oss.TransferFailedEvent:
		log.Printf("\nTransfer Failed, ConsumedBytes: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	default:
	}
}

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

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "examplebucket"
	// Specify the full path of the object. Do not include the bucket name in the full path. 
	objectName := "exampleobject.txt"
	// Specify the full path of the local file in which you want to store the downloaded object. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path. 
	// If you do not specify a local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
	localFile := "D:\\localpath\\examplefile.txt"

	// Query the name of the bucket. 
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Display the progress of the download task. 
	err = bucket.GetObjectToFile(objectName, localFile, oss.Progress(&OssProgressListener{}))
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	log.Println("Transfer Completed.")
}

Referencias

  • Para consultar el código de ejemplo completo utilizado para descargar un objeto como archivo local, visite GitHub.

  • Para obtener más información sobre la operación de API que permite descargar un objeto como archivo local, consulte GetObjectToFile.