Todos os produtos
Search
Central de documentação

Object Storage Service:Primeiros passos com o OSS no CloudBox

Última atualização: Sep 15, 2026

O OSS no CloudBox permite monitorar e processar dados locais. Essa solução é ideal para casos de uso que exigem baixa latência ou gerenciamento unificado de várias filiais. Este tópico descreve as operações básicas do OSS no CloudBox, incluindo a criação de um bucket, o upload de um objeto e o download de um objeto.

Pré-requisitos

  • O OSS no CloudBox está disponível apenas nas regiões China (Hangzhou), China (Shanghai), China (Shenzhen), China (Heyuan), China (Beijing) e China (Chengdu).

  • Você comprou um CloudBox.

  • Você criou uma VPC e um vSwitch para o CloudBox.

  • Você entrou em contato com o suporte técnico para solicitar o tipo de rede SingleTunnel para a VPC do seu CloudBox.

Etapa 1: Crie um bucket

Use the OSS console

  1. Faça logon no console do OSS.

  2. No painel de navegação à esquerda, escolha Data Service > OSS on CloudBox Buckets e clique em Create Bucket no canto superior esquerdo.

  3. Na página Create Bucket, insira um nome para o bucket, mantenha as configurações padrão e clique em OK.

    O nome do bucket deve atender aos seguintes requisitos:

    • Ser exclusivo dentro do CloudBox.

    • Conter apenas letras minúsculas, dígitos e hifens (-).

    • Começar e terminar com uma letra minúscula ou um dígito.

    • Ter entre 3 e 63 caracteres.

Use an Alibaba Cloud SDK

Crie um bucket do OSS no CloudBox usando o OSS SDK para Java, Python ou Go (Java SDK 3.15.0 ou posterior, Python SDK V2 1.1.1 ou posterior, ou Go SDK V2 v1.2.1 ou posterior). No OSS no CloudBox, os SDKs de Python e Go são chamados da mesma forma que no OSS de nuvem pública. Para obter informações sobre como criar um client, consulte SDK support.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CreateBucketRequest;
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 for 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 set.
        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 Cloud Box ID.
        String cloudBoxId = "cb-f8z7yvzgwfkl9q0h****";

        // Create an OSSClient instance.
        // 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 {
            // Create a CreateBucketRequest object.
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);            
                       
            // Set the ACL of the OSS on CloudBox bucket to public-read. The default ACL is private.
            //createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);

            // Create the OSS on CloudBox bucket.
            ossClient.createBucket(createBucketRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request reached OSS but was rejected with an error response.");
            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("Caught a ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            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. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# The region where the CloudBox is located. For example, cn-hangzhou.
cfg.region = "cn-hangzhou"
# The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
cfg.endpoint = "cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com"
# The CloudBox ID.
cfg.cloud_box_id = "cb-xxxx"

client = oss.Client(cfg)

# Create a bucket. The bucket name must be globally unique.
result = client.put_bucket(oss.PutBucketRequest(
    bucket="examplebucket",
    acl="private",
))
print(f"status code: {result.status_code}, request id: {result.request_id}")
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() {
    // The region where the CloudBox is located. For example, cn-hangzhou.
    region := "cn-hangzhou"

    // Obtain access credentials from environment variables. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
    cfg := oss.LoadDefaultConfig().
        WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
        WithRegion(region).
        // The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
        WithEndpoint("cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com").
        // The CloudBox ID.
        WithCloudBoxId("cb-xxxx")

    client := oss.NewClient(cfg)

    // Create a bucket. The bucket name must be globally unique.
    result, err := client.PutBucket(context.TODO(), &oss.PutBucketRequest{
        Bucket: oss.Ptr("examplebucket"),
    })
    if err != nil {
        log.Fatalf("failed to put bucket %v", err)
    }
    log.Printf("put bucket result:%#v\n", result)
}

Use ossutil

Para criar um bucket do OSS no CloudBox com o ossutil, consulte put-bucket.

Use a REST API

Se sua aplicação exigir personalização avançada, chame a REST API diretamente. Nesse caso, escreva código para calcular a assinatura manualmente. Para mais informações, consulte PutBucket.

Etapa 2: Fazer upload de um objeto

Use an Alibaba Cloud SDK

Faça upload de arquivos locais para um bucket do OSS no CloudBox usando o OSS SDK para Java, Python ou Go (Java SDK 3.15.0 ou posterior, Python SDK V2 1.1.1 ou posterior, ou Go SDK V2 v1.2.1 ou posterior). No OSS no CloudBox, os SDKs de Python e Go são chamados da mesma forma que no OSS de nuvem pública. Para obter informações sobre como criar um client, consulte SDK support.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
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. 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. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
        String objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt.
        // If you do not specify a local path, the file is uploaded from the local path of the project to which the sample program belongs.
        String filePath= "D:\\localpath\\examplefile.txt";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        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 {
            // Create a PutObjectRequest object.
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // To set the storage class and access permissions during the upload, see the following sample code.
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // Upload the file.
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            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("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            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. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# The region where the CloudBox is located. For example, cn-hangzhou.
cfg.region = "cn-hangzhou"
# The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
cfg.endpoint = "cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com"
# The CloudBox ID.
cfg.cloud_box_id = "cb-xxxx"

client = oss.Client(cfg)

# Upload data to the specified object.
result = client.put_object(oss.PutObjectRequest(
    bucket="examplebucket",
    key="exampledir/exampleobject.txt",
    body=b"Hello OSS",
))
print(f"status code: {result.status_code}, etag: {result.etag}")
package main

import (
    "context"
    "log"
    "strings"

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

func main() {
    // The region where the CloudBox is located. For example, cn-hangzhou.
    region := "cn-hangzhou"

    // Obtain access credentials from environment variables. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
    cfg := oss.LoadDefaultConfig().
        WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
        WithRegion(region).
        // The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
        WithEndpoint("cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com").
        // The CloudBox ID.
        WithCloudBoxId("cb-xxxx")

    client := oss.NewClient(cfg)

    // Upload data to the specified object.
    result, err := client.PutObject(context.TODO(), &oss.PutObjectRequest{
        Bucket: oss.Ptr("examplebucket"),
        Key:    oss.Ptr("exampledir/exampleobject.txt"),
        Body:   strings.NewReader("Hello OSS"),
    })
    if err != nil {
        log.Fatalf("failed to put object %v", err)
    }
    log.Printf("put object result:%#v\n", result)
}

Use ossutil

Para uploads simples com o ossutil, consulte cp (upload files).

Use a REST API

Se sua aplicação exigir personalização avançada, chame a REST API diretamente. Nesse caso, escreva código para calcular a assinatura manualmente. Para mais informações, consulte PutObject.

Etapa 3: Baixe um objeto

Use an Alibaba Cloud SDK

Baixe objetos usando o OSS SDK para Java, Python ou Go (Java SDK 3.15.0 ou posterior, Python SDK V2 1.1.1 ou posterior, ou Go SDK V2 v1.2.1 ou posterior). No OSS no CloudBox, os SDKs de Python e Go são chamados da mesma forma que no OSS de nuvem pública. Para obter informações sobre como criar um client, consulte SDK support. Os exemplos de código a seguir usam os SDKs de Java, Python e Go.

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. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# The region where the CloudBox is located. For example, cn-hangzhou.
cfg.region = "cn-hangzhou"
# The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
cfg.endpoint = "cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com"
# The CloudBox ID.
cfg.cloud_box_id = "cb-xxxx"

client = oss.Client(cfg)

# Download the object to a local file.
result = client.get_object_to_file(oss.GetObjectRequest(
    bucket="examplebucket",
    key="exampledir/exampleobject.txt",
), "download.txt")
print(f"status code: {result.status_code}, content length: {result.content_length}")
package main

import (
    "context"
    "io"
    "log"

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

func main() {
    // The region where the CloudBox is located. For example, cn-hangzhou.
    region := "cn-hangzhou"

    // Obtain access credentials from environment variables. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
    cfg := oss.LoadDefaultConfig().
        WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
        WithRegion(region).
        // The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
        WithEndpoint("cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com").
        // The CloudBox ID.
        WithCloudBoxId("cb-xxxx")

    client := oss.NewClient(cfg)

    // Download the specified object.
    result, err := client.GetObject(context.TODO(), &oss.GetObjectRequest{
        Bucket: oss.Ptr("examplebucket"),
        Key:    oss.Ptr("exampledir/exampleobject.txt"),
    })
    if err != nil {
        log.Fatalf("failed to get object %v", err)
    }
    defer result.Body.Close()
    data, _ := io.ReadAll(result.Body)
    log.Printf("get object content length:%d\n", len(data))
}

Use ossutil

Para downloads simples com o ossutil, consulte cp (download files).

Use a REST API

Se sua aplicação exigir personalização avançada, chame a REST API diretamente. Nesse caso, escreva código para calcular a assinatura manualmente. Para mais informações, consulte GetObject.