OSS lets you set a per-request bandwidth cap on uploads and downloads. Use this to prevent a single connection from saturating the network and starving other applications.
How it works
Set the x-oss-traffic-limit header on any supported request. OSS enforces the limit for the duration of that connection only — other connections are unaffected.
Supported operations: PutObject, AppendObject, PostObject, CopyObject, UploadPart, UploadPartCopy, GetObject
Parameter constraints:
| Parameter | Unit | Min | Max |
|---|---|---|---|
x-oss-traffic-limit | bit/s | 819,200 (100 KB/s) | 838,860,800 (100 MB/s) |
Choose a throttling method
| Method | When to use | Access type |
|---|---|---|
| SDK request header | Programmatic uploads and downloads | Any (public or private) |
| File URL parameter | Browser or direct URL access | public-read or public-read-write only |
| Signed URL parameter | Temporary access to private objects | Private |
Throttle SDK requests
Set the throttle value on the request object before calling the upload or download method. All examples below set the limit to 100 KB/s (819,200 bit/s).
For examples in other languages, see SDK overview.
Simple upload and download
Multipart upload
Throttle using a file URL
For objects with public-read or public-read-write ACL, append x-oss-traffic-limit=<value> to the object URL.
Example: The following URL throttles downloads of video.mp4 to 100 KB/s:
https://examplebucket.oss-cn-hangzhou.aliyuncs.com/video.mp4?x-oss-traffic-limit=819200Throttle using a signed URL
For private objects, include x-oss-traffic-limit in the signature calculation when generating the signed URL. The parameter is embedded in the URL and enforced when the URL is used.
For examples in other languages, see SDK overview.
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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 {
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
String bucketName = "examplebucket";
String objectName = "exampledir/exampleobject.txt";
String localFileName = "D:\\localpath\\examplefile.txt";
String downLoadFileName = "D:\\localpath\\exampleobject.txt";
// Set the bandwidth limit to 100 KB/s.
int limitSpeed = 100 * 1024 * 8;
String region = "cn-hangzhou";
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Generate a signed URL for upload, valid for 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);
// Upload using the signed URL.
InputStream inputStream = new FileInputStream(localFileName);
ossClient.putObject(signedUrl, inputStream, -1, null, true);
// Generate a signed URL for download, valid for 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);
// Download using the signed URL.
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
<?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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
$provider = new EnvironmentVariableCredentialsProvider();
$endpoint = "yourEndpoint";
$bucket= "examplebucket";
$object = "exampledir/exampleobject.txt";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Set the bandwidth limit to 100 KB/s (819,200 bit/s).
$options = array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
);
// Generate a signed URL for upload, valid for 60 seconds.
$timeout = 60;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT", $options);
print($signedUrl);
// Generate a signed URL for download, valid for 120 seconds.
$timeout = 120;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print($signedUrl);Python
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import OSS_TRAFFIC_LIMIT
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
object_name = 'exampledir/exampleobject.txt'
local_file_name = 'D:\\localpath\\examplefile.txt'
down_file_name = 'D:\\localpath\\exampleobject.txt'
# Set the bandwidth limit to 100 KB/s (819,200 bit/s).
limit_speed = (100 * 1024 * 8)
params = dict()
params[OSS_TRAFFIC_LIMIT] = str(limit_speed)
# Generate a signed URL for upload, valid for 60 seconds.
url = bucket.sign_url('PUT', object_name, 60, params=params)
print('put object url:', url)
# Upload using the signed URL.
result = bucket.put_object_with_url_from_file(url, local_file_name)
print('http response status:', result.status)
# Generate a signed URL for download, valid for 60 seconds.
url = bucket.sign_url('GET', object_name, 60, params=params)
print('get object url:', url)
# Download using the signed URL.
result = bucket.get_object_with_url_to_file(url, down_file_name)
print('http response status:', result.status)Go
package main
import (
"log"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
localFilePath := "D:\\localpath\\exampleobject.txt"
fd, err := os.Open(localFilePath)
if err != nil {
log.Fatalf("Failed to open local file '%s': %v", localFilePath, err)
}
defer fd.Close()
// Set the bandwidth limit to 5 MB/s (41,943,040 bit/s).
traffic := int64(41943040)
objectName := "exampledir/exampleobject.txt"
// Generate a signed URL for upload, valid for 60 seconds.
strURL, err := bucket.SignURL(objectName, oss.HTTPPut, 60, oss.TrafficLimitParam(traffic))
if err != nil {
log.Fatalf("Failed to generate signed URL for uploading '%s': %v", objectName, err)
}
err = bucket.PutObjectWithURL(strURL, fd)
if err != nil {
log.Fatalf("Failed to upload object '%s': %v", objectName, err)
}
// Generate a signed URL for download, valid for 60 seconds.
strURL, err = bucket.SignURL(objectName, oss.HTTPGet, 60, oss.TrafficLimitParam(traffic))
if err != nil {
log.Fatalf("Failed to generate signed URL for downloading '%s': %v", objectName, err)
}
downloadFilePath := "D:\\localpath\\exampleobject.txt"
err = bucket.GetObjectToFileWithURL(strURL, downloadFilePath)
if err != nil {
log.Fatalf("Failed to download object '%s' to '%s': %v", objectName, downloadFilePath, err)
}
log.Println("Upload and download completed successfully")
}C#
using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
var bucketName = "examplebucket";
var objectName = "exampledir/exampleobject.txt";
var objectContent = "More than just cloud.";
var downloadFilename = "D:\\localpath\\examplefile.txt";
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
conf.SignatureVersion = SignatureVersion.V4;
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Generate a signed URL for upload with bandwidth throttling (valid for 1 hour).
var generatePresignedUriRequest = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Put)
{
Expiration = DateTime.Now.AddHours(1),
};
// Set the bandwidth limit to 100 KB/s (819,200 bit/s).
generatePresignedUriRequest.AddQueryParam("x-oss-traffic-limit", "819200");
var signedUrl = client.GeneratePresignedUri(generatePresignedUriRequest);
var buffer = Encoding.UTF8.GetBytes(objectContent);
using (var ms = new MemoryStream(buffer))
{
client.PutObject(signedUrl, ms);
}
Console.WriteLine("Put object by signature succeeded. {0} ", signedUrl.ToString());
var metadata = client.GetObjectMetadata(bucketName, objectName);
var etag = metadata.ETag;
// Generate a signed URL for download with bandwidth throttling.
// Set the bandwidth limit to 100 KB/s (819,200 bit/s).
var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get);
req.AddQueryParam("x-oss-traffic-limit", "819200");
var uri = client.GeneratePresignedUri(req);
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 signature succeeded. {0} ", uri.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}C++
#include <alibabacloud/oss/OssClient.h>
#include <fstream>
using namespace AlibabaCloud::OSS;
int main(void)
{
std::string Endpoint = "yourEndpoint";
std::string Region = "yourRegion";
std::string BucketName = "examplebucket";
std::string ObjectName = "exampledir/exampleobject.txt";
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Generate a signed URL for upload, valid for 1,200 seconds. Set the limit to 100 KB/s (819,200 bit/s). */
std::time_t expires = std::time(nullptr) + 1200;
GeneratePresignedUrlRequest putrequest(BucketName, ObjectName, Http::Put);
putrequest.setExpires(expires);
putrequest.setTrafficLimit(819200);
auto genOutcome = client.GeneratePresignedUrl(putrequest);
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "test cpp sdk";
std::cout << "Signed upload URL:" << genOutcome.result() << std::endl;
auto outcome = client.PutObjectByUrl(genOutcome.result(), content);
/* Generate a signed URL for download, valid for 1,200 seconds. Set the limit to 100 KB/s (819,200 bit/s). */
GeneratePresignedUrlRequest getrequest(BucketName, ObjectName, Http::Get);
getrequest.setExpires(expires);
getrequest.setTrafficLimit(819200);
genOutcome = client.GeneratePresignedUrl(getrequest);
std::cout << "Signed download URL:" << genOutcome.result() << std::endl;
auto goutcome = client.GetObjectByUrl(genOutcome.result());
ShutdownSdk();
return 0;
}