Todos os produtos
Search
Central de documentação

Object Storage Service:Download objects as files (OSS SDK for Go 1.0)

Última atualização: Jul 03, 2026

Este tópico descreve como baixar um objeto de um bucket para o seu computador.

Observações de uso

  • Este tópico utiliza 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 mais sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).

  • Para baixar um objeto como arquivo local, você precisa da permissão oss:GetObject. Para mais detalhes, consulte Conceder uma política personalizada.

Exemplos

O código de exemplo a seguir mostra como baixar o objeto exampleobject.txt do diretório exampledir em um bucket chamado examplebucket para D:\localpath. Após o download, o arquivo local recebe o nome 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.")
}

Cenários comuns

Download condicional

Ao baixar um único objeto de um bucket, especifique condições baseadas na última modificação ou no ETag do objeto. O download ocorre apenas se essas condições forem atendidas. Caso contrário, o sistema retorna um erro e não inicia a operação. Essa abordagem reduz a transmissão de rede desnecessária e o consumo de recursos, melhorando a eficiência do download.

A tabela a seguir descreve as condições disponíveis.

Nota
  • If-Modified-Since e If-Unmodified-Since podem ser usados em conjunto. If-Match e If-None-Match também podem ser combinados.

  • Obtenha o ETag chamando ossClient.getObjectMeta.

Condição

Descrição

Método

IfModifiedSince

Permite o download se o horário especificado for anterior à última modificação do objeto. Caso contrário, retorna 304 Not Modified.

oss.IfModifiedSince

IfUnmodifiedSince

Habilita o download quando o horário especificado for posterior ou igual à última modificação do objeto. Se não atender, retorna 412 Precondition Failed.

oss.IfUnmodifiedSince

IfMatch

Realiza o download se o ETag especificado corresponder ao do objeto. Em caso negativo, retorna 412 Precondition Failed.

oss.IfMatch

IfNoneMatch

Baixa o objeto caso o ETag especificado não corresponda ao do objeto. Senão, retorna 304 Not Modified.

oss.IfNoneMatch

O código de exemplo a seguir ilustra como executar um download 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.")
}

Exibição do progresso do download

Durante o download de um objeto, use a barra de progresso para acompanhar a evolução em tempo real. Esse recurso ajuda a verificar se a tarefa está travada após longos períodos de espera.

O código de exemplo a seguir demonstra como exibir o progresso do download de um objeto chamado exampleobject.txt de um 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.")
}

Referências

  • Para acessar o código de exemplo completo sobre como baixar um objeto como arquivo local, visite o GitHub.

  • Para mais informações sobre a operação de API usada para baixar um objeto como arquivo local, consulte GetObjectToFile.