This topic describes how to quickly download an object from an Object Storage Service (OSS) bucket to a local device.
Precautions
In this topic, the region ID
cn-hangzhou
of China (Hangzhou) is used as an example. By default, the public endpoint is used. If you want to access OSS from another Alibaba Cloud service in the same region as OSS, use the internal endpoint. For more information about the mapping between regions and endpoints supported by OSS, see OSS 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.
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 Policy or Bucket Policy.
API | Action | Definition |
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 definition
func (c *Client) GetObject(ctx context.Context, request *GetObjectRequest, optFns ...func(*Options)) (*GetObjectResult, error)
Request parameters
Parameter | Field type | The description |
ctx | context.Context | The context of the request, which can be used to specify the total duration of the request. |
request | *GetObjectRequest | The parameters of the specific API operation. For more information, see GetObjectRequest. |
optFns | ...func(*Options) | (Optional) The configuration parameters at the API operation level. For more information, see Options. |
Response parameters
Return value name | Field type | The description |
result | *GetObjectResult | The return value of the API operation. This parameter is valid only when the value of err is nil. For more information, see GetObjectResult. |
err | error | The status of the request. If the request fails, the value of err is not nil. |
Sample code
The following sample code demonstrates how to download an object from an OSS bucket to a local device:
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
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 the command line arguments
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 OSSClient instance
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
For the complete sample code about downloading objects to a local device, see GitHub.
For more information about the API operations for downloading objects to a local device, see GetObjectToFile and GetObject.