Todos os produtos
Search
Central de documentação

Object Storage Service:Downloader no OSS SDK for Go 2.0

Última atualização: Jun 23, 2026

Este tópico descreve como baixar objetos usando o módulo Downloader do Object Storage Service (OSS) SDK for Go V2.

Observações de uso

  • O código de exemplo neste tópico usa o ID de região cn-hangzhou da região China (Hangzhou). Por padrão, o endpoint público é utilizado para acessar recursos em um bucket. Para acessar recursos no bucket a partir de outros serviços Alibaba Cloud na mesma região do bucket, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e Endpoints.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais informações sobre como configurar as credenciais de acesso, consulte Configurar credenciais de acesso.

  • Para baixar um objeto, você precisa ter a permissão oss:GetObject. Para mais informações, consulte Conceder uma política personalizada.

Métodos

Downloader

O módulo Downloader do OSS SDK for Go V2 fornece uma operação universal para download de objetos e oculta os detalhes de implementação.

  • O Downloader usa a capacidade subjacente de download por intervalo (range download) para dividir um objeto em partes e baixá-las em paralelo, melhorando o desempenho do download.

  • O Downloader permite realizar downloads resumíveis. Um download resumível registra o progresso e possibilita retomar o download a partir da posição registrada no arquivo de checkpoint em caso de interrupções causadas por desconexões de rede ou encerramento inesperado do programa. É possível retomar o download mesmo após múltiplas tentativas sem sucesso.

A seguir estão os métodos comuns do módulo Downloader:

type Downloader struct {
  ...
}

// Create a Downloader.
func (c *Client) NewDownloader(optFns ...func(*DownloaderOptions)) *Downloader

// Download a object.
func (d *Downloader) DownloadFile(ctx context.Context, request *GetObjectRequest, filePath string, optFns ...func(*DownloaderOptions)) (result *DownloadResult, err error)

Parâmetros da requisição

Parâmetro

Tipo

Descrição

ctx

context.Context

O contexto da requisição. Pode ser usado para especificar a duração total da requisição.

request

*GetObjectRequest

Os parâmetros de uma operação de API específica. Para mais informações, consulte GetObjectRequest.

filePath

string

O caminho do arquivo local.

optFns

...func(*DownloaderOptions)

Os parâmetros opcionais.

Parâmetros comuns de DownloaderOptions

Parâmetro

Tipo

Descrição

PartSize

int64

O tamanho da parte. O valor padrão é 6 MiB.

ParallelNum

int

O número de partes baixadas em paralelo. O valor padrão é 3. Essa configuração aplica-se apenas à chamada atual, sem efeito global.

EnableCheckpoint

bool

Indica se as informações de checkpoint devem ser registradas. Por padrão, não são registradas.

CheckpointDir

string

O caminho do arquivo de checkpoint. Este parâmetro só é válido quando EnableCheckpoint está definido como true. Exemplo: /local/dir/.

VerifyData

bool

Indica se o CRC-64 do objeto baixado deve ser verificado ao retomar o download. Por padrão, o CRC-64 não é verificado. Este parâmetro só é válido quando EnableCheckpoint está definido como true.

UseTempFile

bool

Indica se um arquivo temporário deve ser usado durante o download de um objeto. Por padrão, um arquivo temporário é utilizado. O objeto é baixado para o arquivo temporário e, em seguida, esse arquivo é renomeado para o nome do arquivo de destino.

Ao usar NewDownloader para criar um Downloader, você pode especificar diversos parâmetros de configuração para personalizar o comportamento de download. Também é possível definir parâmetros de configuração individuais a cada chamada de operação de download.

  • Especificar parâmetros de configuração para o Downloader

    d := client.NewDownloader(func(do *oss.DownloaderOptions) {
      do.PartSize = 10 * 1024 * 1024
    })
  • Especificar parâmetros de configuração para cada requisição de download

    request := &oss.GetObjectRequest{Bucket: oss.Ptr("bucket"), Key: oss.Ptr("key")}
    d.DownloadFile(context.TODO(), request, "/local/dir/example", func(do *oss.DownloaderOptions) {
      do.PartSize = 10 * 1024 * 1024
    })

Código de exemplo

O código de exemplo a seguir demonstra como baixar um objeto para um dispositivo local.

package main

import (
	"context"
	"flag"
	"log"

	"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(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "src-object", "", "The name of the source 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 source object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, src object name required")
	}

	// Create an OSS client configuration.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a Downloader.
	d := client.NewDownloader()

	// Create a request to download the object.
	request := &oss.GetObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
	}

	// The path of the local file.
	localFile := "local-file"

	// Execute the request to download the object.
	result, err := d.DownloadFile(context.TODO(), request, localFile)
	if err != nil {
		log.Fatalf("failed to download file %v", err)
	}

	// Print the success response.
	log.Printf("download file %s to local-file successfully, size: %d", objectName, result.Written)
}

Cenários comuns

Usar o Downloader para especificar o tamanho e o número de partes baixadas em paralelo

O código de exemplo a seguir demonstra como especificar o tamanho e o número de partes baixadas em paralelo configurando os parâmetros em DownloaderOptions:

package main

import (
	"context"
	"flag"
	"log"

	"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(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "src-object", "", "The name of the source 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 source object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, src object name required")
	}

	// Create an OSS client configuration.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a Downloader.
	d := client.NewDownloader()

	// Create a request to download the object.
	request := &oss.GetObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
	}

	// The path of the local file.
	localFile := "local-file"

	// Specify downloader options.
	downloaderOptions := func(do *oss.DownloaderOptions) {
		do.PartSize = 20 * 1024 * 1024 // Set the part size to 20 MiB.
		do.ParallelNum = 6            // Set the number of parts that can be downloaded in parallel to 6.
	}

	// Execute the request to download the object.
	result, err := d.DownloadFile(context.TODO(), request, localFile, downloaderOptions)
	if err != nil {
		log.Fatalf("failed to download file %v", err)
	}

	// Print the success response.
	log.Printf("download file %s to local-file successfully, size: %d", objectName, result.Written)
}

Usar o Downloader para ativar o download resumível

O código de exemplo a seguir demonstra como realizar um download resumível configurando DownloaderOptions para um Downloader:

package main

import (
	"context"
	"flag"
	"log"

	"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(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "src-object", "", "The name of the source 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 source object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, src object name required")
	}

	// Create an OSS client configuration.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a Downloader.
	d := client.NewDownloader()

	// Create a request to download the object.
	request := &oss.GetObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
	}

	// The path of the local file.
	localFile := "local-file"

	// Specify downloader options.
	downloaderOptions := func(do *oss.DownloaderOptions) {
		do.EnableCheckpoint = true        // Enable checkpoint recording.
		do.CheckpointDir = "./checkpoint" // Specify the path of the checkpoint file.
		do.UseTempFile = true             // Specify the use of a temporary file.
	}

	// Execute the request to download the object.
	result, err := d.DownloadFile(context.TODO(), request, localFile, downloaderOptions)
	if err != nil {
		log.Fatalf("failed to download file %v", err)
	}

	// Print the success response.
	log.Printf("download file %s to local-file successfully, size: %d", objectName, result.Written)
}

Referências