Download objects to a local device using OSS SDK for Go 2.0
Download objects from an OSS bucket to a local device by using the GetObject or GetObjectToFile method.
Usage notes
-
The sample code uses the region ID
cn-hangzhou(China (Hangzhou)) and the public endpoint. To access the bucket from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about OSS regions and endpoints, see 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 |
|
Downloads an object. |
|
|
When downloading an object, if you specify the object version through versionId, this permission is required. |
|
|
|
When downloading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, this permission is required. |
Method
func (c *Client) GetObject(ctx context.Context, request *GetObjectRequest, optFns ...func(*Options)) (*GetObjectResult, error)
Request parameters
|
Parameter |
Type |
Description |
|
ctx |
context.Context |
The request context. Use this to set the total request timeout. |
|
request |
*GetObjectRequest |
The request parameters. GetObjectRequest. |
|
optFns |
...func(*Options) |
Optional. Operation-level parameter overrides. Options. |
Response parameters
|
Parameter |
Type |
Description |
|
result |
*GetObjectResult |
The operation response. Available when err is nil. GetObjectResult. |
|
err |
error |
The error. Non-nil if the request fails. |
Sample code
Download an object from a bucket to a local file:
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 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(®ion, "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 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 object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Define the path of the output file.
outputFile := "downloaded.file" // Replace the string with the path of the output 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 request to query the object.
request := &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
}
// Query the object and process the results.
result, err := client.GetObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to get object %v", err)
}
defer result.Body.Close() // Close the response body when the function is complete.
// Read all data within the object.
data, err := io.ReadAll(result.Body)
if err != nil {
log.Fatalf("failed to read object %v", err)
}
// Write the data to a 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)
}
Common scenarios
References
-
Complete sample code: GitHub.
-
API reference: GetObjectToFile and GetObject.