When you access objects in Object Storage Service (OSS) by using a client, especially a client on which traffic throttling is difficult to perform, a large amount of bandwidth may be occupied. This affects other applications that access OSS. To prevent this issue, you can use the single-connection bandwidth throttling feature to throttle the bandwidth for operations such as object upload and download. This way, sufficient bandwidth can be reserved for other applications that access OSS.

Usage notes

You can include the x-oss-traffic-limit parameter in the requests to configure bandwidth throttling when you call operations such as PutObject, AppendObject, PostObject, CopyObject, UploadPart, UploadPartCopy, and GetObject. Valid values: 819200 to 838860800. Unit: bit/s.

Perform bandwidth throttling on client requests

You can use only SDKs to throttle the requests that are initiated from clients. The following code provides examples on how to use OSS SDKs for common programming languages to throttle upload or download requests that are initiated from clients. For more information about how to throttle upload or download requests that are initiated from clients by using OSS SDKs for other programming languages, see Overview.

Configure bandwidth throttling for simple upload and download

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.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. The path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. 
        // By default, if the path of the local file is not specified, the local file is uploaded from the path of the project to which the sample program belongs. 
        String localFileName = "D:\\localpath\\examplefile.txt";
        // Specify the full path of the local file to which you want the object to be downloaded. If the specified local file exists, the object to download overwrites the file. Otherwise, a file is created. 
        // If the path for the object is not specified, the downloaded object is saved to the path of the project to which the sample program belongs. 
        String downLoadFileName = "D:\\localpath\\exampleobject.txt";

        // Set the bandwidth limit to 100 KB/s. 
        int limitSpeed = 100 * 1024 * 8;

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Configure bandwidth throttling for object upload. 
            InputStream inputStream = new FileInputStream(localFileName);
            PutObjectRequest PutObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            PutObjectRequest.setTrafficLimit(limitSpeed);
            ossClient.putObject(PutObjectRequest);

            // Configure bandwidth throttling for object download. 
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
            getObjectRequest.setTrafficLimit(limitSpeed);
            File localFile = new File(downLoadFileName);
            ossClient.getObject(getObjectRequest, localFile);
        } 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();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
$object = "exampledir/exampleobject.txt";
// Specify the content of the object. 
$content = "hello world";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);

// Set the bandwidth limit to 100 KB/s, which is equal to 819,200 bit/s. 
$options = array(
      OssClient::OSS_HEADERS => array(
              OssClient::OSS_TRAFFIC_LIMIT => 819200,
));

try {
    // Configure bandwidth throttling for object upload. 
    $ossClient->putObject($bucket, $object, $content, $options);

    // Configure bandwidth throttling for object download. 
    $ossClient->getObject($bucket, $object, $options);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}

print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss')

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (OSS) is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Set yourbucketname to the name of your bucket. 
  bucket: 'yourbucketname'
});

// Configure the speed limit by using the request header. 
const headers = {  
 'x-oss-traffic-limit': 8 * 1024 * 100 // Set the minimum bandwidth to 100 KB/s. 
}

// Configure bandwidth throttling for the object to be uploaded. 
async function put() {
  const result = await client.putStream('file name', 'file stream', {
    headers,
    timeout: 60000 // Set the default timeout period to 60000. Unit: milliseconds. If the duration of an object upload exceeds the timeout period, an exception is thrown. When you configure bandwidth throttling for object uploads, modify the timeout period. 
  })
  console.log(result)
}
put()

// Configure bandwidth throttling for the object to be downloaded. 
async function get() {
  const result = await client.get('file name', {
    headers,
    timeout: 60000 // Set the default timeout period to 60000. Unit: milliseconds. If the duration of an object download exceeds the timeout period, an exception is thrown. When you configure bandwidth throttling for object downloads, modify the timeout period. 
  })
  console.log(result)
}
get()
# -*- coding: utf-8 -*-

import oss2
from oss2.models import OSS_TRAFFIC_LIMIT

# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (OSS) is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')

# Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
object_name = 'exampledir/exampleobject.txt'
# Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. 
local_file_name = 'D:\\localpath\\examplefile.txt'
# Specify the full path of the local file to which you want to download the object. If a file that has the same name already exists in the specified path, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path. 
# If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
down_file_name = 'D:\\localpath\\exampleobject.txt'

# Configure the headers parameter to set the bandwidth limit to 100 KB/s, which is equal to 819,200 bit/s. 
limit_speed = (100 * 1024 * 8)
headers = dict()
headers[OSS_TRAFFIC_LIMIT] = str(limit_speed);

# Configure bandwidth throttling for object upload. 
result = bucket.put_object_from_file(object_name, local_file_name, headers=headers)
print('http response status:', result.status)

# Configure bandwidth throttling for object download. 
result = bucket.get_object_to_file(object_name, down_file_name, headers=headers)
print('http response status:', result.status)
using System.Text;
using Aliyun.OSS;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. The path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
var objectContent = "More than just cloud.";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
    MemoryStream requestContent = new MemoryStream(binaryData);
    // Set the bandwidth limit to 100 KB/s, which is equal to 819200 bit/s. 
    var putRequest = new PutObjectRequest(bucketName, objectName, requestContent)
    {
        TrafficLimit = 100*1024*8
    };
    client.PutObject(putRequest);
    Console.WriteLine("Put object succeeded");

    // Set the bandwidth limit for object download to 100 KB/s , which is equal to 819200 bit/s. 
    var getRequest = new GetObjectRequest(bucketName, objectName)
    {
        TrafficLimit = 100 * 1024 * 8
    };
    var getResult = client.GetObject(getRequest);
    Console.WriteLine("Get object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}
package main

import (
  "fmt"
  "os"
  "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {  

  // Create an OSSClient instance. 
  // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")  
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Specify the bucket name. Example: examplebucket. 
  bucket, err := client.Bucket("examplebucket")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
  // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. 
  // If you do not specify the path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. 
  fd, err := os.Open("D:\\localpath\\examplefile.txt")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
  defer fd.Close()

  // Specify the bandwidth limit for the upload. The value of the parameter must be a number. Default unit: bit/s. In this example, the bandwidth limit is set to 5 MB/s. 
  var traffic int64 = 41943040
  // Configure bandwidth throttling for object upload. 
  // Specify the full path of the object. The full path of the object cannot contain the bucket name. 
  err = bucket.PutObject("exampledir/exampleobject.txt", fd, oss.TrafficLimitHeader(traffic))
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Configure bandwidth throttling for object download. 
  // Specify the full paths of the object and the local file. The full path of the object cannot contain the bucket name. Example of the object path: exampledir/exampleobject.txt. Example of the local file path: D:\\localpath\\exampleobject.txt. 
  err = bucket.GetObjectToFile("exampledir/exampleobject.txt", "D:\\localpath\\exampleobject.txt", oss.TrafficLimitHeader(traffic))
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access Object Storage Service (OSS). */
    /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize resources such as networks. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /* Upload the object. */
    std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>("yourLocalFilename", std::ios::in|std::ios::binary);
    PutObjectRequest putrequest(BucketName, ObjectName,content);
    /* Set the upload bandwidth limit to 100 KB/s. */
    putrequest.setTrafficLimit(819200);
    auto putoutcome = client.PutObject(putrequest);

    /* Download the object to local memory. */
    GetObjectRequest getrequest(BucketName, ObjectName);
    /* Set the download bandwidth limit to 100 KB/s. */
    getrequest.setTrafficLimit(819200);
    auto getoutcome = client.GetObject(getrequest);

    /* Release resources such as networks. */
    ShutdownSdk();
    return 0;
}

Configure bandwidth throttling for multipart upload

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;

public class DemoApi2 {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
        String objectName = "exampledir/exampleobject.txt";
        // Set the bandwidth limit to 100 KB/s. 
        int limitSpeed = 100 * 1024 * 8;

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // Create an InitiateMultipartUpload request. 
            InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);


            // Initialize the multipart upload task. 
            InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
            // Obtain the upload ID, which uniquely identifies the multipart upload task. You can use the upload ID to cancel or query the multipart upload task. 
            String uploadId = upresult.getUploadId();

            // partETags is a set of PartETags. A PartETag consists of an ETag and a part number. 
            List<PartETag> partETags =  new ArrayList<PartETag>();
            // Specify the size of each part, which is used to calculate the number of parts of the object. Unit: byte. 
            final long partSize = 1 * 1024 * 1024L;   // Set the part size to 1 MB. 

            // Specify the full path of the local file. By default, if you do not specify the full path, the local 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 all parts. 
            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 parts that are uploaded. 
                instream.skip(startPos);
                UploadPartRequest uploadPartRequest = new UploadPartRequest();
                uploadPartRequest.setBucketName(bucketName);
                uploadPartRequest.setKey(objectName);
                uploadPartRequest.setUploadId(uploadId);
                uploadPartRequest.setInputStream(instream);
                // Specify the size of each part. The size of each part except for the last part must be equal to or greater than 100 KB. 
                uploadPartRequest.setPartSize(curPartSize);
                // Specify part numbers. Each part has a part number. The number ranges from 1 to 10000. If the number that you specify is not in the range, OSS returns the InvalidArgument error code. 
                uploadPartRequest.setPartNumber( i + 1);
                // Specify the bandwidth limit.
                uploadPartRequest.setTrafficLimit(limitSpeed);
                // Parts are not necessarily uploaded in order and can be uploaded from different OSS clients. OSS sorts the parts based on the part number and combines the parts into a complete object. 
                UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
                // Each time a part is uploaded, OSS returns a result that contains a PartETag. The PartETag is stored in partETags. 
                partETags.add(uploadPartResult.getPartETag());
            }


            // Create a CompleteMultipartUpload request. 
            // When the multipart upload task is complete, you must provide all valid PartETags. After OSS receives the PartETags, OSS verifies all parts one by one. After all parts are verified, OSS combines the parts into a complete object. 
            CompleteMultipartUploadRequest completeMultipartUploadRequest =
                    new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);

            // Complete the multipart upload task. 
            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();
            }
        }
    }
}
<?php
  if (is_file(__DIR__ . '/../autoload.php')) {
  require_once __DIR__ . '/../autoload.php';
  }
  if (is_file(__DIR__ . '/../vendor/autoload.php')) {
  require_once __DIR__ . '/../vendor/autoload.php';
  }

use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Core\OssUtil;

// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
$object = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the path of the local file, the file is uploaded from the local path of the project to which the sample program belongs. 
$uploadFile = "D:\\localpath\\examplefile.txt";

/**
* Step 1. Initiate a multipart upload task and obtain the upload ID. 
*/
try{
  $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

  // Obtain the upload ID. The upload ID is the unique identifier of a multipart upload task. You can perform related operations such as cancel or query the multipart upload task based on the upload ID. 
  $uploadId = $ossClient->initiateMultipartUpload($bucket, $object);
} catch(OssException $e) {
  printf(__FUNCTION__ . ": initiateMultipartUpload FAILED\n");
  printf($e->getMessage() . "\n");
  return;
}
print(__FUNCTION__ . ": initiateMultipartUpload OK" . "\n");
/*
* Step 2: Upload parts. 
*/
$partSize = 10 * 1024 * 1024;
$uploadFileSize = filesize($uploadFile);
$pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
$responseUploadPart = array();
$uploadPosition = 0;
$isCheckMd5 = true;
foreach ($pieces as $i => $piece) {
  $fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
  $toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
  $upOptions = array(
    // Upload the local file. 
    $ossClient::OSS_FILE_UPLOAD => $uploadFile,
    // Specify part numbers. 
    $ossClient::OSS_PART_NUM => ($i + 1),
    // Specify the position from which the multipart upload task starts. 
    $ossClient::OSS_SEEK_TO => $fromPos,
    // Specify the object length. 
    $ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
    // Specify whether to enable MD5 verification. A value of true indicates that MD5 verification is enabled. 
    $ossClient::OSS_CHECK_MD5 => $isCheckMd5,
    // Set the bandwidth limit to 100 KB/s, which is equal to 819,200 bit/s. 
    $options = array(
      OssClient::OSS_HEADERS => array(
        OssClient::OSS_TRAFFIC_LIMIT => 819200,
      ))

  );
  // Enable MD5 verification. 
  if ($isCheckMd5) {
    $contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
    $upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
  }
  try {
    // Upload parts. 
    $responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions);
  } catch(OssException $e) {
    printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n");
    printf($e->getMessage() . "\n");
    return;
  }
  printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} OK\n");
}
// $uploadParts is an array that consists of the ETag and PartNumber of each part. 
$uploadParts = array();
foreach ($responseUploadPart as $i => $eTag) {
  $uploadParts[] = array(
    'PartNumber' => ($i + 1),
    'ETag' => $eTag,
  );
}
/**
* Step 3: Complete the multipart upload task. 
*/
try {
  // All valid $uploadParts are required for the CompleteMultipartUpload operation. After OSS receives the $uploadParts, OSS verifies all parts one by one. After all parts are verified, OSS combines the parts into a complete object. 
  $ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts);
  }  catch(OssException $e) {
  printf(__FUNCTION__ . ": completeMultipartUpload FAILED\n");
  printf($e->getMessage() . "\n");
  return;
  }
  printf(__FUNCTION__ . ": completeMultipartUpload OK\n");
# -*- coding: utf-8 -*-
import os
from oss2 import SizedFileAdapter, determine_part_size
from oss2.headers import OSS_TRAFFIC_LIMIT
from oss2.models import PartInfo
import oss2

# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
key = 'exampledir/exampleobject.txt'
# Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. 
filename = 'D:\\localpath\\examplefile.txt'

total_size = os.path.getsize(filename)
# Use the determine_part_size method to determine the size of each part. 
part_size = determine_part_size(total_size, preferred_size=100 * 1024)

# Initiate a multipart upload task. 
upload_id = bucket.init_multipart_upload(key).upload_id
parts = []

# Configure the headers parameter to set the bandwidth limit to 100 KB/s, which is equal to 819,200 bit/s. 
limit_speed = (100 * 1024 * 8)
headers = dict()
headers[OSS_TRAFFIC_LIMIT] = str(limit_speed);

# Upload the parts one by one. 
with open(filename, 'rb') as fileobj:
    part_number = 1
    offset = 0
    while offset < total_size:
        num_to_upload = min(part_size, total_size - offset)
        # Call the SizedFileAdapter(fileobj, size) method to generate a new object and recalculate the position from which the append operation starts. 
        result = bucket.upload_part(key, upload_id, part_number,
                                    SizedFileAdapter(fileobj, num_to_upload), headers=headers)
        parts.append(PartInfo(part_number, result.etag))

        offset += num_to_upload
        part_number += 1

# Complete the multipart upload task. 
# The following code provides an example on how to configure headers when you complete the multipart upload task: 
headers = dict()
# Specify the access control list (ACL) of the object. In this example, this parameter is set to OBJECT_ACL_PRIVATE, which indicates that the ACL of the object is private. 
# headers["x-oss-object-acl"] = oss2.OBJECT_ACL_PRIVATE
bucket.complete_multipart_upload(key, upload_id, parts, headers=headers)
# bucket.complete_multipart_upload(key, upload_id, parts)

# Verify the result of the multipart upload task. 
with open(filename, 'rb') as fileobj:
    assert bucket.get_object(key).read() == fileobj.read()
package main

import (
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)

func main() {

    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Specify the bucket name. Example: examplebucket. 
    bucket, err := client.Bucket("examplebucket")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Specify the bandwidth limit for the upload. The value of the parameter must be a number. Default unit: bit/s. In this example, the bandwidth limit is set to 5 MB/s. 
    var traffic int64 = 41943040

    // Upload a large object by using multipart upload. 
    // You can split an object into multiple parts based on the object size. In this example, the object is split into three parts. 
    chunks, err := oss.SplitFileByPartNum("localFile", 3)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Open the object. 
    fd, err := os.Open("fileName")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    defer fd.Close()
    // Initiate a multipart upload. 
    imur, err := bucket.InitiateMultipartUpload("exampledir/exampleobject.txt")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Upload parts and configure bandwidth throttling. 
    var parts []oss.UploadPart
    for _, chunk := range chunks {
        fd.Seek(chunk.Offset, os.SEEK_SET)
        part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number, oss.TrafficLimitHeader(traffic))
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
        parts = append(parts, part)
    }
    // Complete the multipart upload. 
    _, err = bucket.CompleteMultipartUpload(imur, parts)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}

Implement bandwidth throttling by using an object URL

For a public-read or public-read-write object, you need only to append the bandwidth throttling parameter x-oss-traffic-limit=<value> after the object URL to implement bandwidth throttling. For example, https://examplebucket.oss-cn-hangzhou.aliyuncs.com/video.mp4?x-oss-traffic-limit=819200 specifies that the upper limit to download the video.mp4 object is 100 KB/s. The following figure shows the effect of bandwidth throttling.video

Perform bandwidth throttling by using a signed URL

To perform bandwidth throttling on a private object, you must add the bandwidth throttling parameter to the signature when you use an SDK to generate a signed URL. The following code provides examples on how to add the bandwidth throttling parameter to a signed URL by using OSS SDKs for common programming languages. For more information about how to add the bandwidth throttling parameter to a signed URL by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.*;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. The path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";

        // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. 
        // By default, if the path of the local file is not specified, the local file is uploaded from the path of the project to which the sample program belongs. 
        String localFileName = "D:\\localpath\\examplefile.txt";

        // Specify the full path of the local file to which you want the object to be downloaded. If the specified local file exists, the object to download overwrites the file. Otherwise, a file is created. 
        // If the path for the object is not specified, the downloaded object is saved to the path of the project to which the sample program belongs. 
        String downLoadFileName = "D:\\localpath\\exampleobject.txt";

        // Set the bandwidth limit to 100 KB/s. 
        int limitSpeed = 100 * 1024 * 8;

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Generate a signed URL used to upload an object with bandwidth throttling configured and set the validity period of the URL to 60 seconds. 
            Date date = new Date();
            date.setTime(date.getTime() + 60 * 1000);
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
            request.setExpiration(date);
            request.setTrafficLimit(limitSpeed);
            URL signedUrl = ossClient.generatePresignedUrl(request);
            System.out.println("put object url" + signedUrl);

            // Configure bandwidth throttling for object upload. 
            InputStream inputStream = new FileInputStream(localFileName);
            ossClient.putObject(signedUrl, inputStream, -1, null, true);

            // Generate a signed URL used to download the object with bandwidth throttling configured and set the validity period of the URL to 60 seconds. 
            date = new Date();
            date.setTime(date.getTime() + 60 * 1000);
            request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
            request.setExpiration(date);
            request.setTrafficLimit(limitSpeed);
            signedUrl = ossClient.generatePresignedUrl(request);
            System.out.println("get object url" + signedUrl);

            // Configure bandwidth throttling for object download. 
            GetObjectRequest getObjectRequest =  new GetObjectRequest(signedUrl, null);
            ossClient.getObject(getObjectRequest, new File(downLoadFileName));
        } 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();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
$object = "exampledir/exampleobject.txt";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);

// Set the bandwidth limit to 100 KB/s, which is equal to 819,200 bit/s. 
$options = array(
        OssClient::OSS_TRAFFIC_LIMIT => 819200,
);

// Generate a signed URL that includes the bandwidth throttling parameter for object upload and set the validity period of the URL to 60 seconds. 
$timeout = 60;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT", $options);
print($signedUrl);

// Generate a signed URL that includes the bandwidth throttling parameter for object download and set the validity period of the URL to 120 seconds. 
$timeout = 120;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print($signedUrl);
# -*- coding: utf-8 -*-

import oss2
from oss2.models import OSS_TRAFFIC_LIMIT

# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')

# Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
object_name = 'exampledir/exampleobject.txt'
# Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. 
local_file_name = 'D:\\localpath\\examplefile.txt'
# Specify the full path of the local file to which you want to download the object. If a file that has the same name already exists in the specified path, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path. 
# If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
down_file_name = 'D:\\localpath\\exampleobject.txt'

# Configure the params parameter to set the bandwidth limit to 100 KB/s, which is equal to 819,200 bit/s. 
limit_speed = (100 * 1024 * 8)
params = dict()
params[OSS_TRAFFIC_LIMIT] = str(limit_speed);

# Generate a signed URL that includes the bandwidth throttling parameter for object upload and set the validity period of the URL to 60 seconds. 
url = bucket.sign_url('PUT', object_name, 60, params=params)
print('put object url:', url)

# Configure bandwidth throttling for object upload. 
result = bucket.put_object_with_url_from_file(url, local_file_name)
print('http response status:', result.status)

# Generate a signed URL that includes the bandwidth throttling parameter for object download and set the validity period of the URL to 60 seconds. 
url = bucket.sign_url('GET', object_name, 60, params=params)
print('get object url:', url)

# Configure bandwidth throttling for object download. 
result = bucket.get_object_with_url_to_file(url, down_file_name)
print('http response status:', result.status)
package main

import (
  "fmt"
  "os"
  "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
  // Create an OSSClient instance. 
  // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret") 
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Specify the bucket name. Example: examplebucket. 
  bucket, err := client.Bucket("examplebucket")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Use the signed URL to upload an object. 
  // Specify the full path of the local file to upload. Example: D:\\localpath\\exampleobject.txt. 
  fd, err := os.Open("D:\\localpath\\exampleobject.txt")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
  defer fd.Close()

  // Specify the bandwidth limit for the upload. The value of the parameter must be a number. Default unit: bit/s. In this example, the bandwidth limit is set to 5 MB/s.   
  var traffic int64 = 41943040
  // Obtain the signed URL that is used to upload the object. 
  // Specify the full path of the object. The full path of the object cannot contain the bucket name. 
  strURL, err := bucket.SignURL("exampledir/exampleobject.txt", oss.HTTPPut, 60, oss.TrafficLimitParam(traffic))
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Upload a local file. 
  err = bucket.PutObjectWithURL(strURL, fd)
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Use the signed URL to download the object. 
  // Obtain the signed URL that is used to download the object. 
  strURL, err = bucket.SignURL("exampledir/exampleobject.txt", oss.HTTPGet, 60, oss.TrafficLimitParam(traffic))
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
  // Specify the full path to which you want to download the object. After the object is downloaded to the specified path, the downloaded object is saved as a local file. 
  err = bucket.GetObjectToFileWithURL(strURL, "D:\\localpath\\exampleobject.txt")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
}
using System.Text;
using Aliyun.OSS;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. The path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
var objectContent = "More than just cloud.";
var downloadFilename  = "D:\\localpath\\examplefile.txt";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{       
    // Generate a signed URL used to upload the object. 
    var generatePresignedUriRequest = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Put)
    {
        Expiration = DateTime.Now.AddHours(1),
    };

    // Set the bandwidth limit to 100 KB/s, which is equal to 819,200 bit/s. 
    generatePresignedUriRequest.AddQueryParam("x-oss-traffic-limit", "819200");

    var signedUrl = client.GeneratePresignedUri(generatePresignedUriRequest);
    // Use the signed URL to upload the object. 
    var buffer = Encoding.UTF8.GetBytes(objectContent);
    using (var ms = new MemoryStream(buffer))
    {
        client.PutObject(signedUrl, ms);
    }
    Console.WriteLine("Put object by signatrue succeeded. {0} ", signedUrl.ToString());


    var metadata = client.GetObjectMetadata(bucketName, objectName);
    var etag = metadata.ETag;
    // Generate a signed URL used to download the object. 
    // Set the bandwidth limit to 100 KB/s, which is equal to 819200 bit/s. 
    var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get);
    req.AddQueryParam("x-oss-traffic-limit", "819200");

    var uri = client.GeneratePresignedUri(req);
    // Use the signed URL to download the object. 
    OssObject ossObject = client.GetObject(uri);
    using (var file = File.Open(downloadFilename, FileMode.OpenOrCreate))
    {
        using (Stream stream = ossObject.Content)
        {
            int length = 4 * 1024;
            var buf = new byte[length];
            do
            {
                length = stream.Read(buf, 0, length);
                file.Write(buf, 0, length);
            } while (length != 0);
        }
    }
    Console.WriteLine("Get object by signatrue succeeded. {0} ", uri.ToString());
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
    /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize resources such as networks. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /* Set the validity period of the signed URL to 1,200 seconds. */
    std::time_t t = std::time(nullptr) + 1200;
    /* Generate the signed URL that is used to upload the object. */
    GeneratePresignedUrlRequest putrequest(BucketName, ObjectName, Http::Put);
    putrequest.setExpires(expires);
     /* Set the upload bandwidth limit to 100 KB/s. */
    putrequest.setTrafficLimit(819200);
    auto genOutcome = client.GeneratePresignedUrl(putrequest);

    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "test cpp sdk";

    /* Use the signed URL to upload the object. */
    auto outcome = client.PutObjectByUrl(genOutcome.result(), content);

    /* Generate the signed URL that is used to download the object. */
    GeneratePresignedUrlRequest getrequest(BucketName, ObjectName, Http::Get);
    getrequest.setExpires(expires);
    /* Set the download bandwidth limit to 100 KB/s. */
    getrequest.setTrafficLimit(819200);
    genOutcome = client.GeneratePresignedUrl(getrequest);

    /* Use the signed URL to download the object. */
    outcome = client.GetObjectByUrl(genOutcome.result());

    /* Release resources such as networks. */
    ShutdownSdk();
    return 0;
}