Download objects from CloudBox

Updated at:

Use the GetObject operation to download an object from an OSS on CloudBox bucket in a single HTTP request. Choose from the Java SDK, ossutil, or the REST API based on your use case.

Use an Alibaba Cloud SDK

You can download objects by using the OSS SDK for Java, Python, or Go (Java SDK 3.15.0 or later, Python SDK V2 1.1.1 or later, or Go SDK V2 v1.2.1 or later). For OSS on CloudBox, the Python and Go SDKs are called in the same way as they are in public cloud OSS. For information about how to create a client, see SDK support. The following code examples use the Java, Python, and Go SDKs.

All requests use Signature Version 4 (V4) and require a CloudBox ID in addition to the standard endpoint and region.

package com.aliyun.oss.demo;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Specify the data endpoint of the OSS on CloudBox bucket.
        String endpoint = "https://cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the OSS on CloudBox bucket. For example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the region where the OSS on CloudBox bucket is located.
        String region = "cn-hangzhou";
        // Specify the ID of the CloudBox.
        String cloudBoxId = "cb-f8z7yvzgwfkl9q0h****";
        // Specify the full path of the object, excluding the bucket name. For example, exampledir/exampleobject.txt.
        String objectName = "exampledir/exampleobject.txt";
        // Specify the local file path to save the downloaded object.
        String pathName = "D:\\localpath\\examplefile.txt";

        // Create an OSSClient instance using Signature Version 4 (V4).
        // Call shutdown() to release resources when the client is no longer needed.
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        conf.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(new DefaultCredentialProvider(credentialsProvider.getCredentials()))
                .clientConfiguration(conf)
                .region(region)
                .cloudBoxId(cloudBoxId)
                .build();

        try {
            // Download the object to the specified local file.
            // If the file exists, it is overwritten. If it does not exist, a new file is created.
            // If you do not specify a local path, the file is saved to the path of the project to which the sample program belongs.
            ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
        } catch (OSSException oe) {
            System.out.println("OSS rejected the request.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Client failed to communicate with OSS.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
import alibabacloud_oss_v2 as oss

# Obtain access credentials from environment variables. Before you run this code example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

# Use the default configuration of the SDK.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region in which the CloudBox is located, such as cn-hangzhou.
cfg.region = "cn-hangzhou"
# Specify the CloudBox ID. After you set the CloudBox ID, the SDK automatically switches the signing product to oss-cloudbox.
cfg.cloud_box_id = "cb-f8z7yvzgwfkl9q0h****"
# Specify the data domain in the CloudboxId.Region.oss-cloudbox.aliyuncs.com format.
cfg.endpoint = "cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com"

# Create an OSS client.
client = oss.Client(cfg)

# Download the object to the specified local file path. If the local file already exists, it is overwritten. Otherwise, a new file is created.
result = client.get_object_to_file(oss.GetObjectRequest(
    bucket="examplebucket",
    key="exampledir/exampleobject.txt",
), "D:\\localpath\\examplefile.txt")

print(f'status code: {result.status_code},'
      f' request id: {result.request_id},'
      f' content length: {result.content_length},'
      f' etag: {result.etag},')
package main

import (
	"context"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this code example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
	// Use the default configuration of the SDK, and specify the region, CloudBox ID, and data domain.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		// Specify the region in which the CloudBox is located, such as cn-hangzhou.
		WithRegion("cn-hangzhou").
		// Specify the data domain in the CloudboxId.Region.oss-cloudbox.aliyuncs.com format.
		WithEndpoint("cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com").
		// Specify the CloudBox ID. After you set the CloudBox ID, the SDK automatically switches the signing product to oss-cloudbox.
		WithCloudBoxId("cb-f8z7yvzgwfkl9q0h****")

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Specify the local file path to which the object is downloaded.
	localFile := "D:\\localpath\\examplefile.txt"

	// Download the object to the specified local file path. If the local file already exists, it is overwritten. Otherwise, a new file is created.
	result, err := client.GetObjectToFile(context.TODO(), &oss.GetObjectRequest{
		Bucket: oss.Ptr("examplebucket"),
		Key:    oss.Ptr("exampledir/exampleobject.txt"),
	}, localFile)
	if err != nil {
		log.Fatalf("failed to get object to file %v", err)
	}

	log.Printf("get object to file result, status code:%d, request id:%s, content length:%v\n",
		result.StatusCode, result.RequestID, result.ContentLength)
}

Use ossutil

For more information about how to perform a simple download using ossutil, see cp (Download files).

Use the REST API

If your application requires custom request handling, call the REST API directly. You must sign requests manually. For more information, see GetObject.