Simple upload for CloudBox

Updated at:

Simple upload uses the PutObject operation to upload a single file (object) smaller than 5 GB. This method is ideal for uploads that can be completed in a single HTTP request.

Prerequisites

An OSS on CloudBox bucket is created. For more information, see Create an OSS on CloudBox bucket.

Usage notes

  • File size limit

    Simple upload supports objects up to 5 GB. To upload objects larger than 5 GB, use multipart upload for CloudBox.

  • Object naming conventions

    • Use UTF-8 encoding.

    • The length must be between 1 and 1,023 characters.

    • The name cannot start with a forward slash (/) or a backslash (\).

  • Access control

    To prevent unauthorized users from uploading data to your OSS on CloudBox buckets, OSS on CloudBox provides OSS on CloudBox bucket ACLs and OSS on CloudBox bucket policies.

  • Prevent objects with the same name from being overwritten

    By default, OSS overwrites an object if you upload a new object with the same name. To prevent objects from being unexpectedly overwritten, you can use the following methods:

    • Enable versioning

      When versioning is enabled, overwritten objects are saved as previous versions. You can restore a previous version of an object at any time. For more information, see OSS on CloudBox versioning.

    • Use a request parameter to prevent overwrites

      Set the x-oss-forbid-overwrite header to true in the upload request. If an object with the same name exists, the upload fails with a FileAlreadyExists error. If omitted or set to false, the existing object is overwritten.

  • Upload performance optimization

    If you upload many objects with names that contain sequential prefixes, such as timestamps or letters, many object indexes might be stored in a single partition. This can decrease the request rate when you send a high volume of requests. To optimize performance, use random prefixes instead of sequential prefixes for object names. For more information, see OSS performance best practices.

Procedure

Use an Alibaba Cloud SDK

You can upload local files to an OSS on CloudBox bucket 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.

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. Before you run this sample, 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 where the OSS on CloudBox bucket is located. Example: 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 endpoint of the OSS on CloudBox bucket, 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)

# Upload a local file. Specify the full path of the object (which cannot contain the bucket name) and the full path of the local file.
result = client.put_object_from_file(oss.PutObjectRequest(
    bucket="examplebucket",
    key="exampledir/exampleobject.txt"
), "D:\\localpath\\examplefile.txt")

print(f'status code: {result.status_code},'
      f' request id: {result.request_id},'
      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() {
	// Use the default configuration of the SDK and obtain access credentials from environment variables.
	// Before you run this sample, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		// Specify the region where the OSS on CloudBox bucket is located. Example: cn-hangzhou.
		WithRegion("cn-hangzhou").
		// Specify the data endpoint of the OSS on CloudBox bucket, 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 full path of the local file.
	localFile := "D:\\localpath\\examplefile.txt"

	// Upload the local file. Specify the bucket name and the full path of the object (which cannot contain the bucket name).
	result, err := client.PutObjectFromFile(context.TODO(), &oss.PutObjectRequest{
		Bucket: oss.Ptr("examplebucket"),
		Key:    oss.Ptr("exampledir/exampleobject.txt"),
	}, localFile)
	if err != nil {
		log.Fatalf("failed to put object from file %v", err)
	}
	log.Printf("put object from file result:%#v\n", result)
}

Use the ossutil command line interface

To perform a simple upload using ossutil, see put-object.

Use a REST API

If your program requires a high degree of customization, you can send REST API requests directly. This method requires you to manually write code to calculate signatures. For more information, see PutObject.