This topic describes how to quickly download an object from an Object Storage Service (OSS) bucket to a local device.
Usage notes
The sample code in this topic uses the region ID
cn-hangzhou
of the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket from other Alibaba Cloud services in the same region in which the bucket is located, 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 the access credentials, see Configure access credentials.
To download an object to a local device, you must have the
oss:GetObject
permission. For more information, see Attach a custom policy to a RAM user.
Method
func (c *Client) GetObject(ctx context.Context, request *GetObjectRequest, optFns ...func(*Options)) (*GetObjectResult, error)
Request parameters
Parameter | Type | 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 a specific API operation. For more information, see GetObjectRequest. |
optFns | ...func(*Options) | Optional. The operation-level parameters. For more information, see Options. |
Response parameters
Parameter | Type | Description |
result | *GetObjectResult | The response to the operation. This parameter is available 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 provides an example on 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 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
Conditional download
Display of the download progress
References
For the complete sample code that is used to download an object to a local device, visit GitHub.
For more information about the API operations that you can call to download an object to a local device, see GetObjectToFile and GetObject.