Multipart upload for OSS on CloudBox

Updated at:

OSS on CloudBox supports multipart upload. You can split an object into multiple parts and upload them separately. After all the parts are uploaded, you can call the CompleteMultipartUpload operation to combine these parts into a complete object.

Prerequisites

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

Scenarios

  • Accelerated upload of large objects: If you want to upload an object whose size is larger than 5 GB, you can use multipart upload to split the object into multiple parts and upload the parts in parallel to accelerate the upload.

  • Network jitters: Multipart upload is suitable for scenarios in which the network condition is poor. If a specific part fails to be uploaded, you need to only re-upload the part. This saves time and bandwidth.

  • Upload pause and resumption: Multipart upload tasks do not expire. You can pause and resume a multipart upload task at any time before the task is complete or canceled.

  • Unknown object size: In scenarios such as video surveillance, the final object sizes may be unknown. In this case, you can use multipart upload to upload the objects.

Process

image

To upload a local file by using multipart upload, perform the following steps:

  1. Call the InitiateMultipartUpload operation to initiate a multipart upload task.

  2. Call the UploadPart operation to upload parts.

    • The parts of the object that you want to upload are sorted based on the part numbers that you specify during the upload. However, parts do not need to be uploaded in order and can be uploaded in parallel. More parts uploaded in parallel do not necessarily accelerate the upload. We recommend that you specify the number of parallel uploads based on your network conditions and the workload of your devices.

    • By default, if you upload the parts of an object but do not call the CompleteMultipartUpload operation to combine the parts into an object, the uploaded parts are not automatically deleted. To cancel the upload task and delete the parts, call the AbortMultipartUpload operation.

  3. Call the CompleteMultipartUpload operation to combine the uploaded parts into an object.

Limits

Limit

Description

Size of an object

Up to 48.8 TB.

Number of parts

1 to 10000.

Size of a part

100 KB to 5 GB. The size of the last part can be less than 100 KB.

Maximum number of parts that can be returned for a single ListParts request

1,000

Maximum number of multipart upload tasks that can be returned for a single ListMultipartUploads request

1,000

Usage notes

  • Optimize upload performance

    If you upload many objects whose names contain sequential prefixes, such as timestamps or letters, the indexes for these objects might be stored in the same partition of the bucket. If many requests are sent to query these objects, the request rate can decrease. To avoid this issue, do not use sequential prefixes in object names when you upload many objects. For more information, see Best practices for OSS performance.

  • Overwrite objects

    Uploading an object with the same name as an existing object overwrites the existing object. You can prevent objects from being accidentally overwritten in the following ways:

    • Enable versioning

      After you enable versioning, overwritten objects are saved as previous versions. You can restore previous versions at any time. For more information, see Versioning for OSS on CloudBox.

    • Include the header used to prevent objects that have the same names from being overwritten in the request: Include the x-oss-forbid-overwrite header in the upload request and set the header to true. This way, when upload an object that has the same name as an existing object is uploaded, the upload fails and the FileAlreadyExists error is returned. For more information, see InitiateMultipartUpload.

  • Delete parts

    When a multipart upload is interrupted, the uploaded parts remain in the bucket. If you no longer need these parts, you can configure a lifecycle rule to automatically delete them. For more information, see Lifecycle rules for OSS on CloudBox.

Procedure

Use an Alibaba Cloud SDK

You can perform multipart uploads 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.

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.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
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 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, for example, exampledir/exampleobject.txt. The full path cannot include the bucket name.
        String objectName = "exampledir/exampleobject.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 an InitiateMultipartUploadRequest object.
            InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);

            // To set request headers when you initialize the multipart upload, see the following sample code.
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // Specify the web page caching behavior for the object.
            // metadata.setCacheControl("no-cache");
            // Specify the name of the object when it is downloaded.
            // metadata.setContentDisposition("attachment;filename=oss_MultipartUpload.txt");
            // Specify the content encoding format of the object.
            // metadata.setContentEncoding(OSSConstants.DEFAULT_CHARSET_NAME);
            // Specify whether to overwrite an existing object that has the same name when you initialize the multipart upload. In this example, this parameter is set to true to prohibit overwriting.
            // metadata.setHeader("x-oss-forbid-overwrite", "true");
            // Specify the server-side encryption method for each part of the object.
            // metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION, ObjectMetadata.KMS_SERVER_SIDE_ENCRYPTION);
            // Specify the encryption algorithm for the object. If you do not specify this parameter, the AES-256 algorithm is used.
            // metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_DATA_ENCRYPTION, ObjectMetadata.KMS_SERVER_SIDE_ENCRYPTION);
            // Specify the customer master key (CMK) that is managed by KMS.
            // metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION_KEY_ID, "9468da86-3509-4f8d-a61e-6eab1eac****");
            // Specify the storage class of the object.
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard);
            // Specify one or more tags for the object.
            // metadata.setHeader(OSSHeaders.OSS_TAGGING, "a:1");
            // request.setObjectMetadata(metadata);

            // Initialize the multipart upload.
            InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
            // The upload ID is returned. It is the unique identifier for the multipart upload event. You can use the upload ID to perform related operations, such as canceling or querying the multipart upload.
            String uploadId = upresult.getUploadId();

            // partETags is a collection of PartETag objects. A PartETag consists of the ETag and part number of a part.
            List<PartETag> partETags =  new ArrayList<PartETag>();
            // The size of each part in bytes. This is used to calculate the number of parts.
            final long partSize = 1 * 1024 * 1024L;   // 1 MB.

            // Specify the full path of the local file. If you do not specify a local path, the file is uploaded from the path of the project to which the sample program belongs.
            final File sampleFile = new File("D:\\localpath\\examplefile.txt");
            long fileLength = sampleFile.length();
            int partCount = (int) (fileLength / partSize);
            if (fileLength % partSize != 0) {
                partCount++;
            }
            // Upload parts in a loop.
            for (int i = 0; i < partCount; i++) {
                long startPos = i * partSize;
                long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
                InputStream instream = new FileInputStream(sampleFile);
                // Skip the uploaded parts.
                instream.skip(startPos);
                UploadPartRequest uploadPartRequest = new UploadPartRequest();
                uploadPartRequest.setBucketName(bucketName);
                uploadPartRequest.setKey(objectName);
                uploadPartRequest.setUploadId(uploadId);
                uploadPartRequest.setInputStream(instream);
                // Set the part size. The minimum size of each part is 100 KB, except for the last part.
                uploadPartRequest.setPartSize(curPartSize);
                // Set the part number. Each uploaded part has a part number that ranges from 1 to 10,000. If a part number is out of this range, OSS returns the InvalidArgument error code.
                uploadPartRequest.setPartNumber( i + 1);
                // Parts do not need to be uploaded in sequence. They can even be uploaded from different clients. OSS combines the parts into a complete object based on their part numbers.
                UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
                // After each part is uploaded, the response from OSS contains a PartETag. The PartETag is saved in partETags.
                partETags.add(uploadPartResult.getPartETag());
            }


            // Create a CompleteMultipartUploadRequest object.
            // When you complete the multipart upload, you must provide all valid partETags. After OSS receives the partETags, it verifies each part. After all parts are verified, OSS combines them into a complete object.
            CompleteMultipartUploadRequest completeMultipartUploadRequest =
                    new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);

            // To set access permissions for the object when you complete the multipart upload, see the following sample code.
            // completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.Private);
            // Specify whether to list all parts that are uploaded for the current upload ID. If you list the parts on the server to merge them into a complete object, the partETags in the CompleteMultipartUploadRequest can be null.
            // Map<String, String> headers = new HashMap<String, String>();
            // If you set x-oss-complete-all to yes, OSS lists all parts that are uploaded for the current upload ID, sorts them by part number, and then completes the multipart upload.
            // If you set x-oss-complete-all to yes, you cannot specify a body. Otherwise, an error is reported.
            // headers.put("x-oss-complete-all","yes");
            // completeMultipartUploadRequest.setHeaders(headers);

            // Complete the multipart upload.
            CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
            System.out.println(completeMultipartUploadResult.getETag());
        } 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();
            }
        }
    }
}
# -*- coding: utf-8 -*-
import os
import alibabacloud_oss_v2 as oss

# Obtain access credentials from environment variables. Before running this code example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
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)

# Specify the name of the bucket, such as examplebucket.
bucket_name = "examplebucket"
# Specify the full path of the object, such as exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
object_name = "exampledir/exampleobject.txt"
# Specify the full path of the local file, such as D:\\localpath\\examplefile.txt.
file_path = "D:\\localpath\\examplefile.txt"

# Initiate the multipart upload task. The returned upload_id uniquely identifies the multipart upload task. You can use the upload_id to perform related operations, such as canceling or querying the multipart upload task.
init_result = client.initiate_multipart_upload(oss.InitiateMultipartUploadRequest(
    bucket=bucket_name,
    key=object_name,
))
upload_id = init_result.upload_id

# The size of each part, which is used to calculate the number of parts of the file. Unit: bytes. In this example, the part size is set to 1 MB.
part_size = 1 * 1024 * 1024
data_size = os.path.getsize(file_path)
part_number = 1
upload_parts = []

# Upload the parts one by one. Each part must be at least 100 KB in size, except for the last part.
with open(file_path, 'rb') as f:
    for start in range(0, data_size, part_size):
        n = part_size
        if start + n > data_size:
            n = data_size - start
        reader = oss.io_utils.SectionReader(oss.io_utils.ReadAtReader(f), start, n)
        up_result = client.upload_part(oss.UploadPartRequest(
            bucket=bucket_name,
            key=object_name,
            upload_id=upload_id,
            part_number=part_number,
            body=reader,
        ))
        # After each part is uploaded, the response contains the ETag of the part, which is saved in upload_parts.
        upload_parts.append(oss.UploadPart(part_number=part_number, etag=up_result.etag))
        part_number += 1

# Sort the parts by part number in ascending order.
parts = sorted(upload_parts, key=lambda p: p.part_number)

# Complete the multipart upload task. After OSS receives the ETags of all parts, OSS verifies each part. After all parts are verified, OSS combines the parts into a complete object.
result = client.complete_multipart_upload(oss.CompleteMultipartUploadRequest(
    bucket=bucket_name,
    key=object_name,
    upload_id=upload_id,
    complete_multipart_upload=oss.CompleteMultipartUpload(
        parts=parts
    ),
))
print(f'etag: {result.etag}')
package main

import (
	"context"
	"io"
	"log"
	"os"

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

func main() {
	// Load the default configuration of the SDK and set the access credentials, region, CloudBox ID, and data domain.
	// Obtain access credentials from environment variables. Before running this code example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	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 name of the bucket, such as examplebucket.
	bucketName := "examplebucket"
	// Specify the full path of the object, such as exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
	objectName := "exampledir/exampleobject.txt"
	// Specify the full path of the local file, such as D:\\localpath\\examplefile.txt.
	filePath := "D:\\localpath\\examplefile.txt"

	// Initiate the multipart upload task. The returned UploadId uniquely identifies the multipart upload task.
	initResult, err := client.InitiateMultipartUpload(context.TODO(), &oss.InitiateMultipartUploadRequest{
		Bucket: oss.Ptr(bucketName),
		Key:    oss.Ptr(objectName),
	})
	if err != nil {
		log.Fatalf("failed to initiate multipart upload %v", err)
	}
	uploadId := initResult.UploadId

	// Open the local file.
	file, err := os.Open(filePath)
	if err != nil {
		log.Fatalf("failed to open file %v", err)
	}
	defer file.Close()

	stat, err := file.Stat()
	if err != nil {
		log.Fatalf("failed to stat file %v", err)
	}
	fileSize := stat.Size()

	// The size of each part, which is used to calculate the number of parts of the file. Unit: bytes. In this example, the part size is set to 1 MB.
	partSize := int64(1 * 1024 * 1024)
	partCount := int(fileSize / partSize)
	if fileSize%partSize != 0 {
		partCount++
	}

	var parts []oss.UploadPart
	// Upload the parts one by one. Each part must be at least 100 KB in size, except for the last part.
	for i := 0; i < partCount; i++ {
		startPos := int64(i) * partSize
		curPartSize := partSize
		if i+1 == partCount {
			curPartSize = fileSize - startPos
		}
		partRequest := &oss.UploadPartRequest{
			Bucket:     oss.Ptr(bucketName),
			Key:        oss.Ptr(objectName),
			// Specify the part number. Valid values: 1 to 10000.
			PartNumber: int32(i + 1),
			UploadId:   uploadId,
			Body:       io.NewSectionReader(file, startPos, curPartSize),
		}
		partResult, err := client.UploadPart(context.TODO(), partRequest)
		if err != nil {
			log.Fatalf("failed to upload part %v", err)
		}
		// After each part is uploaded, the response contains the ETag of the part, which is saved in parts.
		parts = append(parts, oss.UploadPart{
			PartNumber: partRequest.PartNumber,
			ETag:       partResult.ETag,
		})
	}

	// Complete the multipart upload task. After OSS receives the ETags of all parts, OSS combines the parts into a complete object.
	result, err := client.CompleteMultipartUpload(context.TODO(), &oss.CompleteMultipartUploadRequest{
		Bucket:   oss.Ptr(bucketName),
		Key:      oss.Ptr(objectName),
		UploadId: uploadId,
		CompleteMultipartUpload: &oss.CompleteMultipartUpload{
			Parts: parts,
		},
	})
	if err != nil {
		log.Fatalf("failed to complete multipart upload %v", err)
	}
	log.Printf("etag: %v\n", oss.ToString(result.ETag))
}

Use ossutil

If you run the cp command provided by ossutil 2.0 CLI to upload a large local file, ossutil automatically uses multipart upload to upload the local file.

ossutil cp D:/localpath/example.iso oss://examplebucket/desfolder/

To manually upload a local file by using multipart upload, you can use the initiate-multipart-upload, upload-part, and complete-multipart-upload operations together.

API operations

The methods described above are fundamentally implemented based on the RESTful API, which you can directly call if your business requires a high level of customization. To directly call an API, you must include the signature calculation in your code.

  • For information about the API operation that you can call to initiate a multipart upload task, see InitiateMultipartUpload.

  • For information about the API operation that you can call to upload parts, see UploadPart.

  • For information about the API operation that you can call to upload a part by copying data from an existing object, see UploadPartCopy.

  • For information about the API operation that you can call to complete a multipart upload task, see CompleteMultipartUpload.

  • For information about the API operation that you can call to cancel a multipart upload task and delete the parts generated in the task, see AbortMultipartUpload.

  • For more information about the API operation that you can call to list all ongoing multipart upload tasks, see ListMultipartUploads.

  • For information about the API operation that you can call to list all uploaded parts, see ListParts.