All Products
Search
Document Center

Object Storage Service:Download an object to a local file (Go SDK V1)

Last Updated:Nov 28, 2025

This topic describes how to download an object from a bucket to a local file.

Notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Configure OSSClient instances.

  • To download an object to a local file, you must have the oss:GetObject permission. For more information, see Grant custom access policies to a RAM user.

Sample code

The following code shows how to download the exampleobject.txt file from the exampledir folder in the examplebucket bucket to the local path D:\localpath\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.
	// 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 buckets in other regions, set the endpoint to the actual endpoint.
	// 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 buckets in other regions, set the region to the actual region.
	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)
	}

	// Specify the bucket name, for example, examplebucket.
	bucketName := "examplebucket" // Replace 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 and save it to the specified local path. If the specified local file exists, it is overwritten. If the specified local file does not exist, it is created.
	// If you do not specify a local path, the downloaded file is saved to the local path of the project where the sample program resides.
	// Specify the full path of the object, for example, exampledir/exampleobject.txt, and the full path of the local file, for example, D:\\localpath\\examplefile.txt. The full path of the object cannot contain the bucket name.
	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.")
}

Scenarios

Conditional download

You can specify conditions when you download an object from a bucket. These conditions can be based on the object's last modified time or its ETag. An ETag is an identifier for the object's content. The object is downloaded only if the specified conditions are met. Otherwise, an error is returned. Conditional downloads reduce network traffic and improve efficiency.

OSS supports the following conditions:

Note
  • Both If-Modified-Since and If-Unmodified-Since can exist at the same time as object download conditions. Both If-Match and If-None-Match can exist at the same time as object download conditions.

  • You can obtain the ETag by using ossClient.getObjectMeta.

Parameter

Description

How to set

IfModifiedSince

If the specified time is earlier than the actual modification time of the object, the object is downloaded. Otherwise, a 304 Not Modified error is returned.

oss.IfModifiedSince

IfUnmodifiedSince

If the specified time is the same as or later than the actual modification time of the object, the object is downloaded. Otherwise, a 412 Precondition Failed error is returned.

oss.IfUnmodifiedSince

IfMatch

If the specified ETag matches the ETag of the object in OSS, the object is downloaded. Otherwise, a 412 Precondition Failed error is returned.

oss.IfMatch

IfNoneMatch

If the specified ETag does not match the ETag of the object in OSS, the object is downloaded. Otherwise, a 304 Not Modified error is returned.

oss.IfNoneMatch

The following code shows how to perform a conditional download.

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.
	// 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 buckets in other regions, set the endpoint to the actual endpoint.
	// 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 buckets in other regions, set the region to the actual region.
	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)
	}

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

	// Assume that the object was last modified at 18:43:02 on November 21, 2023. If you specify a UTC time that is earlier than this time, the IfModifiedSince condition is met and the download is triggered.
	date := time.Date(2023, time.November, 21, 18, 43, 2, 0, time.UTC)

	// Specify the full path of the object. The full path cannot contain the bucket name.
	objectName := "yourObjectName" // Replace with the actual object name.
	localFilePath := "LocalFile"   // The path of the local file.

	// The condition is not met. The object is not downloaded.
	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 condition is met. The object is downloaded.
	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 a progress bar for a download

When you download an object, you can use a progress bar to view the real-time download progress. This helps you monitor the task and avoid concerns that the download has stalled during long wait times.

The following code shows how to display a progress bar when you download the exampleobject.txt object from the examplebucket bucket.

package main

import (
	"log"
	"sync/atomic"

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

// Define a progress listener.
type OssProgressListener struct {
	lastProgress int64
}

// Define a handler for 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.
	// 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 buckets in other regions, set the endpoint to the actual endpoint.
	// 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 buckets in other regions, set the region to the actual region.
	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("Error: %v", err)
	}

	// Specify the bucket name.
	bucketName := "examplebucket"
	// Specify the full path of the object. The full path cannot contain the bucket name.
	objectName := "exampleobject.txt"
	// Specify the full path of the local file. If the specified local file exists, it is overwritten. If the specified local file does not exist, it is created.
	// If you do not specify a local path, the downloaded file is saved to the local path of the project where the sample program resides.
	localFile := "D:\\localpath\\examplefile.txt"

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

	// Download the object with a progress bar.
	err = bucket.GetObjectToFile(objectName, localFile, oss.Progress(&OssProgressListener{}))
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	log.Println("Transfer Completed.")
}

References

  • For the complete sample code that shows how to download an object to a local file, see GitHub.

  • For more information about the API operation used to download an object to a local file, see GetObjectToFile.