Download objects using OSS SDK for Go 2.0

Updated at:
Copy as MD

You can download objects from a versioning-enabled bucket by using OSS SDK for Go V2.

Notes

  • The sample code uses the China (Hangzhou) region ID cn-hangzhou and the public endpoint. To access the bucket from an Alibaba Cloud service in the same region, use an internal endpoint instead. For more information about supported regions and endpoints, see OSS regions and endpoints.

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

Permissions

By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM policies or Bucket Policy.

API

Action

Description

GetObject

oss:GetObject

Downloads an object.

oss:GetObjectVersion

When downloading an object, if you specify the object version through versionId, this permission is required.

kms:Decrypt

When downloading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, this permission is required.

Note

When you call the GetObject operation to download an object, the following results may be returned:

  • If the current version of the object is a delete marker, OSS returns 404 Not Found.

  • If the version ID of the object is specified in the request, OSS returns the specified version of the object. If the version ID is set to null in the request, OSS returns the version whose version ID is null.

  • If the version ID specified in the request is the version ID of a delete marker, OSS returns 405 Method Not Allowed.

Sample code

The following sample code shows how to download objects from a versioning-enabled bucket.

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 global variables.
var (
	region     string // The region in which your bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line 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, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the name of the object is specified.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Specify the path of the output file.
	outputFile := "downloaded.file" // Replace this parameter with the path in which you want to save the 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 query request.
	request := &oss.GetObjectRequest{
		Bucket:    oss.Ptr(bucketName),      // The name of the bucket
		Key:       oss.Ptr(objectName),      // The name of the object
		VersionId: oss.Ptr("yourVersionId"), // The version ID of the object
	}

	// Perform the query operation and process the result.
	result, err := client.GetObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get object %v", err)
	}
	defer result.Body.Close() // Make sure that the response body is closed when the function is complete.

	// Read the entire file.
	data, err := io.ReadAll(result.Body)
	if err != nil {
		log.Fatalf("failed to read object %v", err)
	}

	// Write the content to the 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)
}

References

  • For the complete sample code for downloading objects, visit GitHub sample.

  • For more information about the GetObject operation, see GetObject.