Tous les produits
Search
Centre de documentation

Object Storage Service:Démarrer avec OSS sur CloudBox

Dernière mise à jour :Sep 15, 2026

OSS sur CloudBox vous permet de surveiller et de traiter vos données locales. Cette solution est idéale pour les cas d'utilisation nécessitant une faible latence ou une gestion unifiée de plusieurs succursales. Cette rubrique décrit les opérations de base d'OSS sur CloudBox, notamment la création d'un bucket, le chargement d'un objet et son téléchargement.

Prérequis

  • OSS sur CloudBox est disponible uniquement dans les régions Chine (Hangzhou), Chine (Shanghai), Chine (Shenzhen), Chine (Heyuan), Chine (Pékin) et Chine (Chengdu).

  • Vous avez acheté un CloudBox.

  • Vous avez créé un VPC et un vSwitch pour le CloudBox.

  • Contactez le support technique afin de demander un type de réseau SingleTunnel pour le VPC de votre CloudBox.

Étape 1 : Créer un bucket

Utiliser la console OSS

  1. Connectez-vous à la console OSS.

  2. Dans le volet de navigation de gauche, choisissez Data Service > OSS on CloudBox Buckets, puis cliquez sur Create Bucket dans le coin supérieur gauche.

  3. Sur la page Create Bucket, saisissez un nom de bucket, acceptez les paramètres par défaut, puis cliquez sur OK.

    Le nom du bucket doit répondre aux exigences suivantes :

    • Le nom du bucket doit être unique au sein du CloudBox.

    • Le nom ne peut contenir que des lettres minuscules, des chiffres et des traits d'union (-).

    • Le nom doit commencer et se terminer par une lettre minuscule ou un chiffre.

    • La longueur du nom doit être comprise entre 3 et 63 caractères.

Utiliser un SDK Alibaba Cloud

Créez un bucket OSS sur CloudBox à l'aide du SDK OSS pour Java, Python ou Go (SDK Java 3.15.0 ou version ultérieure, SDK Python V2 1.1.1 ou version ultérieure, ou SDK Go V2 v1.2.1 ou version ultérieure). Pour OSS sur CloudBox, les SDK Python et Go s'utilisent de la même manière que pour OSS dans le cloud public. Pour savoir comment créer un client, consultez la section Prise en charge des SDK.

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)
}

Utiliser ossutil

Pour créer un bucket OSS sur CloudBox avec ossutil, consultez la commande put-bucket.

Utiliser une API REST

Si votre application nécessite une personnalisation poussée, appelez directement l'API REST. Vous devrez écrire du code pour calculer manuellement la signature. Pour plus d'informations, consultez l'opération PutBucket.

Étape 2 : Charger un objet

Utiliser un SDK Alibaba Cloud

Chargez des fichiers locaux vers un bucket OSS sur CloudBox à l'aide du SDK OSS pour Java, Python ou Go (SDK Java 3.15.0 ou version ultérieure, SDK Python V2 1.1.1 ou version ultérieure, ou SDK Go V2 v1.2.1 ou version ultérieure). Pour OSS sur CloudBox, les SDK Python et Go s'utilisent de la même manière que pour OSS dans le cloud public. Pour savoir comment créer un client, consultez la section Prise en charge des SDK.

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)
}

Utiliser ossutil

Pour des chargements simples avec ossutil, consultez la commande cp (charger des fichiers).

Utiliser une API REST

Si votre application nécessite une personnalisation poussée, appelez directement l'API REST. Vous devrez écrire du code pour calculer manuellement la signature. Pour plus d'informations, consultez l'opération PutObject.

Étape 3 : Télécharger un objet

Utiliser un SDK Alibaba Cloud

Téléchargez des objets à l'aide du SDK OSS pour Java, Python ou Go (SDK Java 3.15.0 ou version ultérieure, SDK Python V2 1.1.1 ou version ultérieure, ou SDK Go V2 v1.2.1 ou version ultérieure). Pour OSS sur CloudBox, les SDK Python et Go s'utilisent de la même manière que pour OSS dans le cloud public. Pour savoir comment créer un client, consultez la section Prise en charge des SDK. Les exemples de code suivants utilisent les SDK Java, Python et 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))
}

Utiliser ossutil

Pour des téléchargements simples avec ossutil, consultez la commande cp (télécharger des fichiers).

Utiliser une API REST

Si votre application nécessite une personnalisation poussée, appelez directement l'API REST. Vous devrez écrire du code pour calculer manuellement la signature. Pour plus d'informations, consultez l'opération GetObject.