tencent cloud

Video on Demand

Release Notes and Announcements
Release Notes
Announcements
Product Introduction
Overview
Product Features
Features
Strengths
Scenarios
Solutions
Professional Edition
Introduction to Video On Demand Professional Edition
Quick Start
Console Guide
Development Guide
Purchase Guide
Billing Overview
Billing Modes
Purchase Guide
Viewing Bills
Renewal
Overdue Policy
Refund Policy
Getting Started
Console Guide
Console Overview
Service Overview
Application Management
Media Management
Package Management
License Management
Real-Time Log Analysis
Practical Tutorial
Media Upload
Smart Cold Storage of VOD Media Asset Files
Video Processing
Distribution and Playback
How to Receive Event Notification
How to Migrate Files from Origin Server to VOD
Live Recording
How to Pull from Custom Origin Servers
How to Use EdgeOne to Distribute Content in VOD
Development Guide
Media Upload
Media Processing
Video AI
Event Notification
Video Playback
Media Encryption and Copyright Protection
Broadcast Channel
CAM
Media File Download
Subapplication System
Error Codes
Player SDK
Overview
Basic Concepts
Features
Free Demo
Free Trial License
Purchase Guide
SDK Download
Licenses
Player Guide
Integration (UI Included)
Integration (No UI)
Advanced Features
API Documentation
Player Adapter
Player SDK Policy
Server APIs
History
Introduction
API Category
Other APIs
Media Processing APIs
Task Management APIs
Media Upload APIs
Media Management APIs
Event Notification Relevant API
Media Categorization APIs
Domain Name Management APIs
Distribution APIs
AI-based Sample Management APIs
Region Management APIs
Data Statistics APIs
Carousel-Related APIs
Just In Time Transcode APIs
No longer recommended APIs
Making API Requests
AI-based image processing APIs
Parameter Template APIs
Task Flow APIs
Data Types
Error Codes
Video on Demand API 2024-07-18
FAQs
Mobile Playback
Fees
Video Upload
Video Publishing
Video Playback
Web Playback
Full Screen Playback
Statistics
Access Management
Cold Storage
Agreements
Service Level Agreement
VOD Policy
Privacy Policy
Data Processing And Security Agreement
Contact Us
Glossary

Server-side Upload Guide

PDF
Focus Mode
Font Size
Last updated: 2025-09-09 11:56:43
This document provides guidance for server-side uploads to the Professional Edition application.

Applicable Scenarios

Developers uploading files stored on their backend servers to the Professional Edition storage via API or SDK. This document explains how to upload files using AWS S3 SDK.

Upload Methods

The server must upload via Professional Edition preset domains. Supported methods:
Upload Method
Upload Domain
Authentication
Supported Operations
Bucket Preset Domain
[BucketId].vodpro.[Region].eovod.com
AccessKeys (Recommended)
Upload to specified bucket
Credentials
Upload to specified bucket
Application Preset Domain
[SubAppId].vodpro-upload.com
Credentials
Upload to specified bucket
Nearby upload to buckets in any region within the application

Bucket Preset Domain

The Professional Edition provides an internet access domain for each bucket to upload files to specific buckets.

Uploading Files Using AccessKeys via AWS S3 SDK

Below demonstrates how to upload files to Professional Edition buckets using AccessKey in common programming languages.
Assumptions: Professional Edition App ID = 1234567890, Bucket Region = ap-guangzhou, Bucket ID = bucketid1
Example domain: bucketid1.vodpro.ap-guangzhou.eovod.com

Preparations

1. ​Create Professional Edition App and Bucket​.
Create in VOD Console.
Refer to:
​2. Obtain App-level AccessKeys Pair​.
Get AccessKeyId and SecretAccessKey from App Key Management.
Refer to: Key Management

Upload Examples

Code implementations for initializing S3 clients and uploading files:
GO
Java
C++
Python
// Package main
// This example uses AWS SDK for Go v2 service/s3 v1.72.3
// Versions v1.73.0+ require disabling S3 default integrity protection
// Ref: https://github.com/aws/aws-sdk-go-v2/discussions/2960
package main

import (
"context"
"errors"
"fmt"
"log"
"net/url"
"os"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
smep "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/logging"
)

// customEndpointResolverV2 Custom endpoint resolver
type customEndpointResolverV2 struct{}

// ResolveEndpoint Custom endpoint resolution
func (r *customEndpointResolverV2) ResolveEndpoint(ctx context.Context,
params s3.EndpointParameters) (smep.Endpoint, error) {
if params.Bucket == nil || params.Region == nil {
return smep.Endpoint{}, errors.New("invalid endpoint param")
}
return smep.Endpoint{
URI: url.URL{
Scheme: "https",
Host: fmt.Sprintf("%s.vodpro.ap-guangzhou.eovod.com", *params.Bucket),
},
}, nil
}

func main() {
// Initialize S3 client
s3cli := s3.New(s3.Options{
Credentials: credentials.NewStaticCredentialsProvider(
"AccessKeyId", // Enter AccessKeyId
"SecretAccessKey", // Enter SecretAccessKey
""), // No session token needed for AccessKey
EndpointResolverV2: new(customEndpointResolverV2),
UsePathStyle: false,
Logger: logging.NewStandardLogger(os.Stdout),
ClientLogMode: aws.LogRequest | aws.LogResponse,
Region: "auto",
})

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

// Upload file to S3
uploader := manager.NewUploader(s3cli, func(u *manager.Uploader) {
u.PartSize = 10 * 1024 * 1024 // 10MB part size
u.Concurrency = 5 // Concurrent upload threads
})
result, err := uploader.Upload(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String("bucketid1"), // Bucket ID
Key: aws.String("upload/demo.mp4"), // Object key
Body: file,
})

if err != nil {
log.Fatalf("failed to upload file: %v", err)
return
}
log.Printf("etag: %s", *result.ETag) // Get file ETag
}
// This example is implemented using AWS SDK for Java v2 service/s3 v2.31.35.
// AWS SDK for Java 2.30.0 and later require disabling S3's default integrity protection.
// Reference: https://github.com/aws/aws-sdk-java-v2/issues/5801
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.core.checksums.RequestChecksumCalculation;
import software.amazon.awssdk.core.checksums.ResponseChecksumValidation;

import java.io.File;
import java.net.URI;
import java.util.concurrent.CompletableFuture;

public class Main {
public static void main(String[] args) {
S3AsyncClient s3AsyncClient = null;
S3TransferManager transferManager = null;

try {
// Professional Edition application AccessKey AccessKeyId
AwsBasicCredentials credentials = AwsBasicCredentials.create(
"AccessKeyId", // Professional Edition application permanent AccessKeyId
"SecretAccessKey" // Professional Edition application permanent SecretAccessKey
);
String region = "ap-guangzhou"; // Professional Edition application bucket region
String bucketId = "bucketid1"; // Professional Edition application bucket ID
String filePath = "demo.mp4"; // Local file path
String key = "upload/demo.mp4"; // File path in bucket
String endpointUrl = String.format("https://vodpro.%s.eovod.com", region); // Bucket-level preset domain endpoint

// Build S3 async client with custom endpoint
s3AsyncClient = S3AsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(credentials)) // Set credentials provider
.endpointOverride(URI.create(endpointUrl)) // Set endpoint
.region(Region.of("auto")) // Must be set to "auto"
.httpClient(NettyNioAsyncHttpClient.builder().build()) // Set HTTP client
.serviceConfiguration(S3Configuration.builder()
.pathStyleAccessEnabled(false) // Set path style access, bucket level must explicitly disable PathStyle mode
.build())
.requestChecksumCalculation(RequestChecksumCalculation.WHEN_REQUIRED)
.responseChecksumValidation(ResponseChecksumValidation.WHEN_REQUIRED)
.build();

// Create S3TransferManager with S3 async client
transferManager = S3TransferManager.builder()
.s3Client(s3AsyncClient)
.build();

File fileToUpload = new File(filePath);

// Create upload request with transfer listener for progress tracking
UploadFileRequest uploadRequest = UploadFileRequest.builder()
.putObjectRequest(builder -> builder
.bucket(bucketId)
.key(key))
.addTransferListener(LoggingTransferListener.create())
.source(fileToUpload)
.build();

// Start upload
CompletableFuture<Void> future = transferManager.uploadFile(uploadRequest)
.completionFuture()
.thenAccept(response -> {
System.out.println("Upload successful! ETag: " + response.response().eTag());
});

// Wait for upload to complete
future.join();

System.out.println("Upload task completed");
} catch (Exception e) {
System.err.println("Upload failed: " + e.getMessage());
e.printStackTrace();
} finally {
// Release resources
try {
if (transferManager != null) {
transferManager.close();
}
if (s3AsyncClient != null) {
s3AsyncClient.close();
}
System.out.println("Resources released");
} catch (Exception e) {
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}
// This example is implemented using AWS SDK for C++ v1.11.560.
// AWS SDK for C++ v1.11.486 and later require disabling S3's default integrity protection.
// Reference: https://github.com/aws/aws-sdk-cpp/issues/3253
#include <aws/core/Aws.h>
#include <aws/core/auth/AWSCredentials.h>
#include <aws/core/client/ClientConfiguration.h>
#include <aws/s3/S3Client.h>
#include <aws/transfer/TransferManager.h>
#include <iostream>

int main()
{
// AWS SDK initialization
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Info;
Aws::InitAPI(options);

{
// Define authentication and endpoint information
const Aws::String accessKeyId = "AccessKeyId"; // Fill in AccessKeyId from VOD Professional key pair
const Aws::String secretAccessKey = "SecretAccessKey"; // Fill in SecretAccessKey from VOD Professional key pair
const Aws::String region = "ap-guangzhou"; // Bucket region
const Aws::String bucketId = "bucketid1"; // Bucket ID in VOD Professional Edition
const Aws::String keyName = "upload/demo.mp4"; // File path in bucket
const Aws::String filePath = "demo.mp4"; // Local file path

// Configure client
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = "auto"; // Must be set to "auto"
clientConfig.scheme = Aws::Http::Scheme::HTTPS; // Use HTTPS protocol
clientConfig.enableEndpointDiscovery = false; // Disable endpoint discovery
clientConfig.verifySSL = true; // Enable SSL certificate verification
clientConfig.endpointOverride = "vodpro." + region + ".eovod.com"; // Bucket-level preset domain
// Disable integrity check
clientConfig.checksumConfig.requestChecksumCalculation = Aws::Client::RequestChecksumCalculation::WHEN_REQUIRED;
clientConfig.checksumConfig.responseChecksumValidation = Aws::Client::ResponseChecksumValidation::WHEN_REQUIRED;

// Set authentication information
Aws::Auth::AWSCredentials credentials(accessKeyId, secretAccessKey); // Fill in VOD Professional AccessKey

// Create S3 client
auto s3Client = Aws::MakeShared<Aws::S3::S3Client>(
"S3Client",
credentials,
clientConfig,
Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never, // Disable payload signing
true // Bucket-level domain requires explicit VirtualAddressing
);

// Create thread pool executor
auto executor = Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>("executor", 10);

// Configure TransferManager
Aws::Transfer::TransferManagerConfiguration transferConfig(executor.get());
transferConfig.s3Client = s3Client;

// Set part size to 10MB
transferConfig.bufferSize = 10 * 1024 * 1024;

// Create TransferManager
auto transferManager = Aws::Transfer::TransferManager::Create(transferConfig);

std::cout << "Starting file upload: " << filePath << " to " << bucketId << "/" << keyName << std::endl;

// Perform upload
auto uploadHandle = transferManager->UploadFile(
filePath, // Local file path
bucketId, // Bucket ID
keyName, // Object key (storage path)
"application/octet-stream", // Content type
Aws::Map<Aws::String, Aws::String>() // Metadata
);

// Wait for upload to complete
uploadHandle->WaitUntilFinished();

// Check upload status
if (uploadHandle->GetStatus() == Aws::Transfer::TransferStatus::COMPLETED)
{
std::cout << "File upload completed successfully!" << std::endl;
}
else
{
auto lastError = uploadHandle->GetLastError();
std::cerr << "File upload failed: " << lastError.GetMessage() << std::endl;
}
}

// Clean up SDK resources
Aws::ShutdownAPI(options);
return 0;
}
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
This example is implemented using AWS SDK for Python v1.38.7.
Boto3 AWS SDK for Python v1.36.0 and later require disabling S3's default integrity protection.
Reference: https://github.com/boto/boto3/issues/4392
"""

import boto3
from botocore.config import Config
from botocore.exceptions import ClientError

# Constant definitions
REGION = "ap-guangzhou" # Bucket region
BUCKET_ID = "bucketid1" # Fill in bucket ID in VOD Professional Edition
FILE_PATH = "demo.mp4" # Local file path
OBJECT_KEY = "upload/demo.mp4" # File path in bucket

# Create S3 client
s3_client = boto3.client(
"s3",
aws_access_key_id="AccessKeyId", # Fill in AccessKeyId from key pair
aws_secret_access_key="SecretAccessKey", # Fill in SecretAccessKey from key pair
endpoint_url=f"https://vodpro.{REGION}.eovod.com", # Bucket-level preset upload domain
region_name="auto", # Must be set to "auto"
config=Config(
s3={"addressing_style": "virtual"}, # Use virtual hosted-style
request_checksum_calculation="when_required", # Boto3 AWS SDK for Python v1.36.0+ require disabling S3's default integrity protection
response_checksum_validation="when_required", # Boto3 AWS SDK for Python v1.36.0+ require disabling S3's default integrity protection
),
)

try:
# Upload file
response = s3_client.upload_file(
Bucket=BUCKET_ID, # Fill in bucket ID in VOD Professional Edition
Key=OBJECT_KEY, # File path in bucket
Filename=FILE_PATH, # Local file path
)
print(response)
except ClientError as e:
print(f"Error: {e}")
Note:
When using AWS SDK, confirm data integrity protection features.
When using bucket preset internet domains, the path must be in VirtualStyle format.

Upload Files Using Credentials with AWS S3 SDK

Below is an introduction to uploading files to a Professional Edition application bucket using credentials in common programming languages.
Assume the Professional Edition application ID is 1234567890, the bucket region is ap-guangzhou, and the bucket ID is bucketid1.
The example bucket access domain is: bucketid1.vodpro.ap-guangzhou.eovod.com.

Upload Steps

Temporary credentials are typically used in scenarios requiring high key security.
Server Uploading Files to Professional Edition Storage Using Temporary Credentials
Server Uploading Files to Professional Edition Storage Using Temporary Credentials

1. Apply for upload credentials: Server calls Professional Edition service's Create Application Storage Temporary Access Credentials interface.
2. Upload files: Server uses credentials to upload files to Professional Edition storage.

Preparation

1. Create the Professional Edition application and bucket in the VOD Console. For specific steps, refer to Quick Start and Create Bucket.
2. Obtain Tencent Cloud account AccessKey pair:
2.1 Log in to Tencent Cloud Console, select Cloud Access Management > Access Key > API Keys, enter the "API Key Management" page.
2.2 Obtain Cloud API key. If you haven't created a key, click New Key to create a pair of SecretId and SecretKey.

Upload Files

Apply for Upload Credentials
Apply for credentials to upload upload/demo.mp4 to bucketid1 bucket.
GO
Java
C++
Python
// Package main
package main

import (
"context"
"encoding/json"
"fmt"
"log"
"net/url"

"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
vod20240718 "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/vod/v20240718"
)

const (
appId = 251000000 // Tencent Cloud account APPID
subAppId = 1234567890 // VOD Professional Edition application APPID
bucketId = "bucketid1" // VOD Professional Edition application bucket ID
fileKey = "upload/demo.mp4" // File KEY in storage after upload, including full path and filename
)

// createStorageCredentialsPolicy create storage credential policy
type createStorageCredentialsPolicy struct {
Statement []policyStatement `json:"statement"`
Version string `json:"version"`
}

// policyStatement policy statement
type policyStatement struct {
Action []string `json:"action"`
Effect string `json:"effect"`
Resource []string `json:"resource"`
}

// cred credentials
type cred struct {
AccessKeyId string
SecretAccessKey string
SessionToken string
}

// getCredential obtain credentials
func getCredential(context.Context) (*cred, error) {
// 1. Obtain credentials
// 1.1 Initialize Tencent Cloud API object
credential := common.NewCredential(
"SecretId", // Tencent Cloud account SecretId
"SecretKey", // Tencent Cloud account SecretKey
)
prof := profile.NewClientProfile()
vodClient, err := vod20240718.NewClient(credential, "ap-guangzhou", prof)
if err != nil {
log.Fatalf("create VOD client fail: %+v", err)
return nil, fmt.Errorf("create VOD client fail: %w", err)
}

// 1.2 Construct temporary credential request
policy := createStorageCredentialsPolicy{
Statement: []policyStatement{{
Action: []string{ // Currently only supported actions
"name/vod:PutObject",
"name/vod:ListParts",
"name/vod:PostObject",
"name/vod:CreateMultipartUpload",
"name/vod:UploadPart",
"name/vod:CompleteMultipartUpload",
"name/vod:AbortMultipartUpload",
"name/vod:ListMultipartUploads",
},
Effect: "allow",
Resource: []string{
fmt.Sprintf("qcs::vod:%s:uid/%d:prefix//%d/%s/%s",
"ap-guangzhou", // Bucket region
appId, // Tencent Cloud account APPID
subAppId, // VOD Professional Edition application APPID
bucketId, // VOD Professional Edition application bucket ID
fileKey, // File KEY in storage after upload
),
},
}},
Version: "2.0",
}
req := vod20240718.NewCreateStorageCredentialsRequest()
req.SubAppId = common.Uint64Ptr(subAppId)
policyStr, _ := json.Marshal(policy)
req.Policy = common.StringPtr(url.QueryEscape(string(policyStr)))

// 1.3 Apply for upload credentials
resp, err := vodClient.CreateStorageCredentials(req)
if err != nil {
log.Fatalf("create storage credentials fail: %+v", err)
return nil, fmt.Errorf("create storage credentials fail: %w", err)
}
log.Printf("create storage credentials success: %+v", resp)
creds := resp.Response.Credentials
return &cred{
AccessKeyId: *creds.AccessKeyId,
SecretAccessKey: *creds.SecretAccessKey,
SessionToken: *creds.SessionToken,
}, nil
}
// This example is implemented based on AWS SDK for Java v2 service/s3 v2.31.35.
// For AWS SDK for Java version 2.30.0 and later, the default integrity protection for S3 must be disabled.
// Reference: https://github.com/aws/aws-sdk-java-v2/issues/5801
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.core.checksums.RequestChecksumCalculation;
import software.amazon.awssdk.core.checksums.ResponseChecksumValidation;

import java.io.File;
import java.net.URI;
import java.util.concurrent.CompletableFuture;

public class Main {
public static void main(String[] args) {
S3AsyncClient s3AsyncClient = null;
S3TransferManager transferManager = null;

try {
// 1. Get credentials
CredentialHelper.Cred cred = CredentialHelper.getCredential();
System.out.println("Temporary credentials obtained successfully. AccessKeyId: " + cred.getAccessKeyId());

// 2. Create session credentials
AwsSessionCredentials sessionCredentials = AwsSessionCredentials.create(
cred.getAccessKeyId(),
cred.getSecretAccessKey(),
cred.getSessionToken()
);

String region = "ap-guangzhou";
String bucketId = "bucketid1";
String filePath = "demo.mp4";
String key = "upload/demo.mp4";
String endpointUrl = String.format("https://vodpro.%s.eovod.com", region);

// 3. Build S3AsyncClient with checksum protection disabled
s3AsyncClient = S3AsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(sessionCredentials))
.endpointOverride(URI.create(endpointUrl))
.region(Region.of("auto"))
.httpClient(NettyNioAsyncHttpClient.builder().build())
.serviceConfiguration(
S3Configuration.builder()
.pathStyleAccessEnabled(false)
.build()
)
// Critical fix - disable CRC32C integrity protection
.requestChecksumCalculation(RequestChecksumCalculation.NONE)
.responseChecksumValidation(ResponseChecksumValidation.DISABLED)
.build();

// 4. Create transfer manager
transferManager = S3TransferManager.builder()
.s3Client(s3AsyncClient)
.build();

// 5. Validate file
File fileToUpload = new File(filePath);
if (!fileToUpload.exists()) {
throw new RuntimeException("File does not exist: " + filePath);
}

// 6. Prepare upload request
UploadFileRequest uploadRequest = UploadFileRequest.builder()
.putObjectRequest(b -> b
.bucket(bucketId)
.key(key))
.addTransferListener(LoggingTransferListener.create())
.source(fileToUpload)
.build();

// 7. Execute upload
System.out.println("Starting file upload...");
CompletableFuture<Void> future = transferManager.uploadFile(uploadRequest)
.completionFuture()
.thenAccept(response -> {
System.out.println("Upload successful! ETag: " + response.response().eTag());
});

// 8. Wait for completion
future.join();
System.out.println("Upload task completed");

} catch (Exception e) {
System.err.println("Upload failed: " + e.getMessage());
e.printStackTrace();
} finally {
// 9. Cleanup resources
try {
if (transferManager != null) transferManager.close();
if (s3AsyncClient != null) s3AsyncClient.close();
System.out.println("Resources released");
} catch (Exception e) {
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}
#include <tencentcloud/core/TencentCloud.h>
#include <tencentcloud/core/profile/ClientProfile.h>
#include <tencentcloud/core/profile/HttpProfile.h>
#include <tencentcloud/core/Credential.h>
#include <tencentcloud/vod/v20240718/VodClient.h>
#include <tencentcloud/vod/v20240718/model/CreateStorageCredentialsRequest.h>
#include <tencentcloud/vod/v20240718/model/CreateStorageCredentialsResponse.h>
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

const uint64_t APP_ID = 251000000; // Tencent Cloud Account APPID
const uint64_t SUB_APP_ID = 1234567890; // VOD Professional Application APPID
const std::string BUCKET_ID = "bucketid1"; // VOD Professional Storage Bucket ID
const std::string REGION = "ap-guangzhou"; // VOD Professional Bucket Region
const std::string OBJECT_KEY = "upload/demo.mp4"; // Storage Object KEY for authorization

// Credential structure
struct Credential
{
std::string accessKeyId;
std::string secretAccessKey;
std::string sessionToken;
};

// URL encoding function
std::string UrlEncode(const std::string &value)
{
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;

for (char c : value)
{
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
{
escaped << c;
}
else
{
escaped << std::uppercase;
escaped << '%' << std::setw(2) << int((unsigned char)c);
escaped << std::nouppercase;
}
}

return escaped.str();
}

// Obtain credentials
Credential GetCredential()
{
// Initialize Tencent Cloud SDK
TencentCloud::InitAPI();

// Create VOD client
TencentCloud::Credential credential("SecretId", "SecretKey"); // Enter your Tencent Cloud SecretId and SecretKey
TencentCloud::HttpProfile httpProfile;
TencentCloud::ClientProfile clientProfile;
clientProfile.SetHttpProfile(httpProfile);

TencentCloud::Vod::V20240718::VodClient client(credential, "ap-guangzhou", clientProfile);

// Build policy
json policy_json = {
{"statement", {{{"action", {"name/vod:PutObject", "name/vod:ListParts", "name/vod:PostObject",
"name/vod:CreateMultipartUpload", "name/vod:UploadPart",
"name/vod:CompleteMultipartUpload", "name/vod:AbortMultipartUpload",
"name/vod:ListMultipartUploads"}},
{"effect", "allow"},
{"resource", {"qcs::vod:" + REGION + ":uid/" + std::to_string(APP_ID) +
":prefix//" + std::to_string(SUB_APP_ID) + "/" + BUCKET_ID + "/" + OBJECT_KEY}}}}
},
{"version", "2.0"}};
std::string policy = policy_json.dump();

// Create request object
TencentCloud::Vod::V20240718::Model::CreateStorageCredentialsRequest req;
req.SetSubAppId(SUB_APP_ID);
req.SetPolicy(UrlEncode(policy));

// Send request
auto outcome = client.CreateStorageCredentials(req);
if (!outcome.IsSuccess())
{
std::cerr << "Failed to get storage credentials: " << outcome.GetError().GetErrorMessage() << std::endl;
TencentCloud::ShutdownAPI();
exit(1);
}

// Extract credentials
auto response = outcome.GetResult();
auto creds = response.GetCredentials();

Credential result;
result.accessKeyId = creds.GetAccessKeyId();
result.secretAccessKey = creds.GetSecretAccessKey();
result.sessionToken = creds.GetSessionToken();

// Clean up Tencent Cloud SDK
TencentCloud::ShutdownAPI();

return result;
}
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import urllib.parse
from typing import NamedTuple

from tencentcloud.common import credential
from tencentcloud.common.profile import client_profile
from tencentcloud.vod.v20240718 import vod_client, models

# Constants
APP_ID = 251000000 # Tencent Cloud account APPID
SUB_APP_ID = 1234567890 # VOD Professional Application APPID
BUCKET_ID = "bucketid1" # VOD Professional Storage Bucket ID
OBJECT_KEY = "upload/demo.mp4" # File KEY for storage after upload
REGION = "ap-guangzhou" # Region

class Credential(NamedTuple):
"""Temporary credential for storage access"""
access_key_id: str
secret_access_key: str
session_token: str

def get_credential() -> Credential:
"""Obtain credentials for VOD storage access"""
# 1. Initialize Tencent Cloud API client
cred = credential.Credential(
"SecretId", # Tencent Cloud account SecretId
"SecretKey", # Tencent Cloud account SecretKey
)
prof = client_profile.ClientProfile()
vod_cli = vod_client.VodClient(cred, REGION, prof)

# 2. Prepare policy for requesting credentials
policy = {
"statement": [
{
"action": [
"name/vod:PutObject",
"name/vod:ListParts",
"name/vod:PostObject",
"name/vod:CreateMultipartUpload",
"name/vod:UploadPart",
"name/vod:CompleteMultipartUpload",
"name/vod:AbortMultipartUpload",
"name/vod:ListMultipartUploads",
],
"effect": "allow",
"resource": [
f"qcs::vod:{REGION}:uid/{APP_ID}:prefix//{SUB_APP_ID}/{BUCKET_ID}/{OBJECT_KEY}"
],
}
],
"version": "2.0",
}

# 3. Create credential request
req = models.CreateStorageCredentialsRequest()
req.SubAppId = SUB_APP_ID
req.Policy = urllib.parse.quote(json.dumps(policy))

# 4. Request temporary storage credentials
resp = vod_cli.CreateStorageCredentials(req)
creds = resp.Credentials
return Credential(
access_key_id=creds.AccessKeyId,
secret_access_key=creds.SecretAccessKey,
session_token=creds.SessionToken,
)
File Upload
Common languages initialize the S3 client and upload files to the bucket as shown below:
GO
Java
C++
Python
// Package main
// This example is implemented using AWS SDK for Go v2 service/s3 v1.72.3.
// AWS SDK for Go v2 service/s3 v1.73.0 and later require disabling S3's default integrity protection.
// Reference: https://github.com/aws/aws-sdk-go-v2/discussions/2960
package main

import (
"context"
"errors"
"fmt"
"log"
"net/url"
"os"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
smep "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/logging"
)

type customEndpointResolverV2 struct {
}

// ResolveEndpoint custom endpoint
func (r *customEndpointResolverV2) ResolveEndpoint(ctx context.Context,
params s3.EndpointParameters) (smep.Endpoint, error) {
if params.Bucket == nil || params.Region == nil {
return smep.Endpoint{}, errors.New("invalid endpoint param")
}
return smep.Endpoint{
URI: url.URL{
Scheme: "https",
Host: fmt.Sprintf(
"%s.vodpro.ap-guangzhou.eovod.com",
*params.Bucket, // Fill in bucket ID in VOD Professional Edition
),
},
}, nil
}

func main() {
// 1. Obtain credentials
cred, err := getCredential(context.Background())
if err != nil {
log.Fatalf("get credential fail: %v", err)
return
}

// 2. Upload file using credentials
// 2.1 Create s3 client
s3cli := s3.New(s3.Options{
Credentials: credentials.NewStaticCredentialsProvider(
cred.AccessKeyId, // Fill in AccessKeyId from credentials
cred.SecretAccessKey, // Fill in SecretAccessKey from credentials
cred.SessionToken, // Fill in SessionToken from credentials
),
EndpointResolverV2: new(customEndpointResolverV2), // Custom endpoint
UsePathStyle: false, // Disable path style requests
Logger: logging.NewStandardLogger(os.Stdout), // Log to stdout
ClientLogMode: aws.LogRequest | aws.LogResponse, // Log request and response headers
Region: "auto", // Must be set to "auto"
})

// 2.2 Open local file
file, err := os.Open("demo.mp4") // Local file path
if err != nil {
log.Fatalf("failed to open file: %v", err)
return
}
defer file.Close()

// 2.3 Upload file to S3
// 2.3.1 Create uploader
uploader := manager.NewUploader(s3cli, func(u *manager.Uploader) {
u.PartSize = 10 * 1024 * 1024 // Set part size to 10MB
u.Concurrency = 5 // Set concurrent upload parts
})
// 2.3.2 Upload file
result, err := uploader.Upload(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String(bucketId), // Set Bucket to bucket ID in VOD Professional Edition
Key: aws.String(fileKey), // Media file path in bucket
Body: file,
})

if err != nil {
log.Fatalf("failed to upload file: %v", err)
return
}
log.Printf("etag: %s", *result.ETag) // Get uploaded file etag
}
// This example is implemented using AWS SDK for Java v2 service/s3 v2.31.35.
// AWS SDK for Java 2.30.0 and later require disabling S3's default integrity protection.
// Reference: https://github.com/aws/aws-sdk-java-v2/issues/5801
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.core.checksums.RequestChecksumCalculation;
import software.amazon.awssdk.core.checksums.ResponseChecksumValidation;

import java.io.File;
import java.net.URI;
import java.util.concurrent.CompletableFuture;

public class Main {
public static void main(String[] args) {
S3AsyncClient s3AsyncClient = null;
S3TransferManager transferManager = null;

try {
// 1. Obtain credentials
CredentialHelper.Cred cred = CredentialHelper.getCredential();
System.out.println("Obtained credentials, AccessKeyId: " + cred.getAccessKeyId());

// 2. Create session credentials (with temporary token)
AwsSessionCredentials sessionCredentials = AwsSessionCredentials.create(
cred.getAccessKeyId(), // Temporary credential AccessKeyId
cred.getSecretAccessKey(), // Temporary credential SecretAccessKey
cred.getSessionToken() // Temporary credential SessionToken
);

String region = "ap-guangzhou"; // Professional Edition bucket region
String bucketId = "bucketid1"; // Professional Edition bucket ID
String filePath = "demo.mp4"; // Local file path
String key = "upload/demo.mp4"; // File path in bucket
String endpointUrl = String.format("https://vodpro.%s.eovod.com", region); // Bucket-level preset domain endpoint

// 3. Build S3 async client with custom endpoint
s3AsyncClient = S3AsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(sessionCredentials)) // Set credentials provider
.endpointOverride(URI.create(endpointUrl)) // Set endpoint
.region(Region.of("auto")) // Set region to auto
.httpClient(NettyNioAsyncHttpClient.builder().build()) // Set HTTP client
.serviceConfiguration(S3Configuration.builder()
.pathStyleAccessEnabled(false) // Set path style access, bucket level must explicitly disable PathStyle mode
.build())
.requestChecksumCalculation(RequestChecksumCalculation.WHEN_REQUIRED)
.responseChecksumValidation(ResponseChecksumValidation.WHEN_REQUIRED)
.build();

// 4. Create S3TransferManager with S3 async client
transferManager = S3TransferManager.builder()
.s3Client(s3AsyncClient)
.build();

// 5. Prepare file for upload
File fileToUpload = new File(filePath);
if (!fileToUpload.exists()) {
throw new RuntimeException("File not found: " + filePath);
}

// 6. Create upload request with transfer listener for progress tracking
UploadFileRequest uploadRequest = UploadFileRequest.builder()
.putObjectRequest(builder -> builder
.bucket(bucketId)
.key(key))
.addTransferListener(LoggingTransferListener.create())
.source(fileToUpload)
.build();

// 7. Start upload
System.out.println("Starting file upload...");
CompletableFuture<Void> future = transferManager.uploadFile(uploadRequest)
.completionFuture()
.thenAccept(response -> {
System.out.println("Upload successful! ETag: " + response.response().eTag());
});

// 8. Wait for upload to complete
future.join();

System.out.println("Upload task completed");
} catch (Exception e) {
System.err.println("Upload failed: " + e.getMessage());
e.printStackTrace();
} finally {
// Release resources
try {
if (transferManager != null) {
transferManager.close();
}
if (s3AsyncClient != null) {
s3AsyncClient.close();
}
System.out.println("Resources released");
} catch (Exception e) {
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}
// This example is implemented using AWS SDK for C++ v1.11.560.
// AWS SDK for C++ v1.11.486 and later require disabling S3's default integrity protection.
// Reference: https://github.com/aws/aws-sdk-cpp/issues/3253
#include <aws/core/Aws.h>
#include <aws/core/auth/AWSCredentials.h>
#include <aws/core/client/ClientConfiguration.h>
#include <aws/s3/S3Client.h>
#include <aws/transfer/TransferManager.h>
#include <iostream>
#include <string>

// Reference credential struct from get_cred.cpp
struct Credential
{
std::string accessKeyId;
std::string secretAccessKey;
std::string sessionToken;
};

// Reference function from get_cred.cpp
extern Credential GetCredential();

int main()
{
// AWS SDK initialization
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Info;
Aws::InitAPI(options);

{
// Get credentials
std::cout << "Getting credentials..." << std::endl;
Credential cred = GetCredential();
std::cout << "Successfully obtained credentials, access key Id: " << cred.accessKeyId << std::endl;

// Define endpoint information
const Aws::String region = "ap-guangzhou"; // VOD Professional Edition bucket region
const Aws::String bucketId = "bucketid1"; // VOD Professional Edition bucket ID
const Aws::String keyName = "upload/demo.mp4"; // File path in bucket
const Aws::String filePath = "demo.mp4"; // Local file path

// Configure client
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = "auto"; // Must be set to "auto"
clientConfig.scheme = Aws::Http::Scheme::HTTPS; // Use HTTPS protocol
clientConfig.enableEndpointDiscovery = false; // Disable endpoint discovery
clientConfig.verifySSL = true; // Enable SSL certificate verification
clientConfig.endpointOverride = "vodpro." + region + ".eovod.com"; // Bucket-level preset domain
// Disable integrity check
clientConfig.checksumConfig.requestChecksumCalculation = Aws::Client::RequestChecksumCalculation::WHEN_REQUIRED;
clientConfig.checksumConfig.responseChecksumValidation = Aws::Client::ResponseChecksumValidation::WHEN_REQUIRED;

// Set authentication information (using credentials)
Aws::Auth::AWSCredentials credentials(
cred.accessKeyId.c_str(),
cred.secretAccessKey.c_str(),
cred.sessionToken.c_str());

// Create S3 client
auto s3Client = Aws::MakeShared<Aws::S3::S3Client>(
"S3Client",
credentials,
clientConfig,
Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never, // Disable payload signing
true // Bucket-level domain requires explicit VirtualAddressing
);

// Create thread pool executor
auto executor = Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>("executor", 10);

// Configure TransferManager
Aws::Transfer::TransferManagerConfiguration transferConfig(executor.get());
transferConfig.s3Client = s3Client;

// Set part size to 10MB
transferConfig.bufferSize = 10 * 1024 * 1024;

// Create TransferManager
auto transferManager = Aws::Transfer::TransferManager::Create(transferConfig);

std::cout << "Starting file upload: " << filePath << " to " << bucketId << "/" << keyName << std::endl;

// Perform upload
auto uploadHandle = transferManager->UploadFile(
filePath, // Local file path
bucketId, // Bucket ID
keyName, // Object key (storage path)
"application/octet-stream", // Content type
Aws::Map<Aws::String, Aws::String>() // Metadata
);

// Wait for upload to complete
uploadHandle->WaitUntilFinished();

// Check upload status
if (uploadHandle->GetStatus() == Aws::Transfer::TransferStatus::COMPLETED)
{
std::cout << "File upload completed successfully!" << std::endl;
}
else
{
auto lastError = uploadHandle->GetLastError();
std::cerr << "File upload failed: " << lastError.GetMessage() << std::endl;
}
}

// Clean up SDK resources
Aws::ShutdownAPI(options);
return 0;
}
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
This example is implemented using AWS SDK for Python v1.38.7.
Boto3 AWS SDK for Python v1.36.0 and later require disabling S3's default integrity protection.
Reference: https://github.com/boto/boto3/issues/4392
"""

import boto3
from botocore.config import Config
from botocore.exceptions import ClientError

from get_cred import get_credential, REGION, BUCKET_ID, OBJECT_KEY

# Constant definitions
FILE_PATH = "demo.mp4"

try:
# 1. Obtain credentials
cred = get_credential()

# 2. Create S3 client
s3_client = boto3.client(
"s3",
aws_access_key_id=cred.access_key_id, # Temporary credential AccessKeyId
aws_secret_access_key=cred.secret_access_key, # Temporary credential SecretAccessKey
aws_session_token=cred.session_token, # Temporary credential SessionToken
endpoint_url=f"https://vodpro.{REGION}.eovod.com", # Bucket-level preset upload domain
region_name="auto", # Must be set to "auto"
config=Config(
s3={"addressing_style": "virtual"}, # Use virtual hosted-style
request_checksum_calculation="when_required", # Boto3 v1.36.0+ require disabling default integrity protection
response_checksum_validation="when_required", # Boto3 v1.36.0+ require disabling default integrity protection
),
)

# 3. Upload file
response = s3_client.upload_file(
Bucket=BUCKET_ID, # Fill in bucket ID in VOD Professional Edition
Key=OBJECT_KEY, # File path in bucket
Filename=FILE_PATH, # Local file path
)
print(response)
except ClientError as e:
print(f"Error: {e}")
Note:
When using AWS SDK, confirm data integrity protection features.
When using bucket preset internet domains, the path must be in VirtualStyle format.

Application Preset Domain

Professional Edition presets an internet upload acceleration domain for each application, which can be used to upload to all buckets within the application.

Upload Files Using Credentials with AWS S3 SDK

Below is an introduction to how to adapt common programming languages to upload files to Professional Edition application buckets.
Assume the Professional Edition application ID is 1234567890, the bucket region is ap-guangzhou, and the bucket ID is bucketid1. The example application upload acceleration domain is: 1234567890.vodpro-upload.com.

Preparation

1. Create the Professional Edition application and bucket in the VOD Console. For specific steps, refer to Quick Start and Create Bucket.
2. Obtain Tencent Cloud account AccessKey pair
2.1 Log in to Tencent Cloud Console, select Cloud Access Management > Access Key > API Keys, enter the "API Key Management" page.
2.2 Obtain Cloud API key. If you haven't created a key, click New Key to create a pair of SecretId and SecretKey.

Upload Example

Apply for Upload Credentials
GO
Java
C++
Python
// Package main
package main

import (
"context"
"encoding/json"
"fmt"
"log"
"net/url"

"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
vod20240718 "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/vod/v20240718"
)

const (
appId = 251000000 // Tencent Cloud account APPID
subAppId = 1234567890 // VOD Professional Edition application APPID
fileKey = "upload/demo.mp4" // File KEY to apply permissions for
bucketId = "auto" // VOD Professional Edition bucket ID, "auto" means automatically select nearby bucket
region = "auto" // VOD Professional Edition bucket region, "auto" means automatically select nearby region
)

// createStorageCredentialsPolicy create storage credential policy
type createStorageCredentialsPolicy struct {
Statement []policyStatement `json:"statement"`
Version string `json:"version"`
}

// policyStatement policy statement
type policyStatement struct {
Action []string `json:"action"`
Effect string `json:"effect"`
Resource []string `json:"resource"`
}

// cred credentials
type cred struct {
AccessKeyId string
SecretAccessKey string
SessionToken string
}

// getCredential obtain credentials
func getCredential(context.Context) (*cred, error) {
// 1. Obtain credentials
// 1.1 Initialize Tencent Cloud API object
credential := common.NewCredential(
"SecretId", // Tencent Cloud account SecretId
"SecretKey", // Tencent Cloud account SecretKey
)
prof := profile.NewClientProfile()
vodClient, err := vod20240718.NewClient(credential, "ap-guangzhou", prof)
if err != nil {
log.Fatalf("create VOD client fail: %+v", err)
return nil, fmt.Errorf("create VOD client fail: %w", err)
}

// 1.2 Construct temporary credential request
policy := createStorageCredentialsPolicy{
Statement: []policyStatement{{
Action: []string{ // Currently only supported actions
"name/vod:PutObject",
"name/vod:ListParts",
"name/vod:PostObject",
"name/vod:CreateMultipartUpload",
"name/vod:UploadPart",
"name/vod:CompleteMultipartUpload",
"name/vod:AbortMultipartUpload",
"name/vod:ListMultipartUploads",
},
Effect: "allow",
Resource: []string{
fmt.Sprintf("qcs::vod:%s:uid/%d:prefix//%d/%s/%s",
region, // Nearby region upload
appId, // Tencent Cloud account APPID
subAppId, // VOD Professional Edition application APPID
bucketId, // Nearby region bucket
fileKey, // File KEY in storage after upload
),
},
}},
Version: "2.0",
}
req := vod20240718.NewCreateStorageCredentialsRequest()
req.SubAppId = common.Uint64Ptr(subAppId)
policyStr, _ := json.Marshal(policy)
req.Policy = common.StringPtr(url.QueryEscape(string(policyStr)))

// 1.3 Apply for upload credentials
resp, err := vodClient.CreateStorageCredentials(req)
if err != nil {
log.Fatalf("create storage credentials fail: %+v", err)
return nil, fmt.Errorf("create storage credentials fail: %w", err)
}
log.Printf("create storage credentials success: %+v", resp)
creds := resp.Response.Credentials
return &cred{
AccessKeyId: *creds.AccessKeyId,
SecretAccessKey: *creds.SecretAccessKey,
SessionToken: *creds.SessionToken,
}, nil
}
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.vod.v20240718.VodClient;
import com.tencentcloudapi.vod.v20240718.models.CreateStorageCredentialsRequest;
import com.tencentcloudapi.vod.v20240718.models.CreateStorageCredentialsResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
* Credential helper class to obtain temporary storage credentials
*/
public class CredentialHelper {
// Constant definitions
private static final long APP_ID = 251000000; // Tencent Cloud account APPID
private static final long SUB_APP_ID = 1234567890; // VOD Professional Application APPID
private static final String BUCKET_ID = "auto"; // VOD Professional storage bucket ID, 'auto' enables automatic bucket selection
private static final String FILE_KEY = "upload/demo.mp4"; // Storage object key with full path, e.g., upload/demo.mp4
private static final String REGION = "auto"; // VOD Professional bucket region, 'auto' enables automatic region selection

/**
* Credential object holding credentials
*/
public static class Cred {
private final String accessKeyId;
private final String secretAccessKey;
private final String sessionToken;

public Cred(String accessKeyId, String secretAccessKey, String sessionToken) {
this.accessKeyId = accessKeyId;
this.secretAccessKey = secretAccessKey;
this.sessionToken = sessionToken;
}

public String getAccessKeyId() {
return accessKeyId;
}

public String getSecretAccessKey() {
return secretAccessKey;
}

public String getSessionToken() {
return sessionToken;
}
}

/**
* Obtains temporary storage credentials
*
* @return Temporary credential object
* @throws Exception If credential retrieval fails
*/
public static Cred getCredential() throws Exception {
try {
// 1. Initialize Tencent Cloud API client
Credential credential = new Credential("SecretId", "SecretKey"); // Tencent Cloud SecretId and SecretKey
ClientProfile clientProfile = new ClientProfile(); // Client configuration
VodClient vodClient = new VodClient(credential, "ap-guangzhou", clientProfile); // Create VodClient instance

// 2. Construct and encode policy
String policyJson = createPolicyJson();
String encodedPolicy = URLEncoder.encode(policyJson, StandardCharsets.UTF_8.name());

// 3. Create and send request
CreateStorageCredentialsRequest req = new CreateStorageCredentialsRequest();
req.setSubAppId(SUB_APP_ID); // VOD Professional Application APPID
req.setPolicy(encodedPolicy); // Policy string

// 4. Get response and return credentials
CreateStorageCredentialsResponse resp = vodClient.CreateStorageCredentials(req);

return new Cred(
resp.getCredentials().getAccessKeyId(),
resp.getCredentials().getSecretAccessKey(),
resp.getCredentials().getSessionToken());
} catch (TencentCloudSDKException e) {
System.err.println("Failed to obtain storage credentials: " + e.getMessage());
throw new Exception("Storage credential retrieval failed", e);
}
}

/**
* Creates policy JSON string using org.json library
*
* @return Policy JSON string
*/
private static String createPolicyJson() {
// Build resource path
String resource = String.format(
"qcs::vod:%s:uid/%d:prefix//%d/%s/%s",
REGION,
APP_ID,
SUB_APP_ID,
BUCKET_ID,
FILE_KEY);

// Build action list
String[] actions = {
"name/vod:PutObject",
"name/vod:ListParts",
"name/vod:PostObject",
"name/vod:CreateMultipartUpload",
"name/vod:UploadPart",
"name/vod:CompleteMultipartUpload",
"name/vod:AbortMultipartUpload",
"name/vod:ListMultipartUploads"
};

// Build JSON using JSONObject
JSONObject policy = new JSONObject();
policy.put("version", "2.0");

JSONArray statements = new JSONArray();
JSONObject statement = new JSONObject();

JSONArray actionArray = new JSONArray();
for (String action : actions) {
actionArray.put(action);
}
statement.put("action", actionArray);

statement.put("effect", "allow");

JSONArray resources = new JSONArray();
resources.put(resource);
statement.put("resource", resources);

statements.put(statement);
policy.put("statement", statements);

return policy.toString();
}
}
#include <tencentcloud/core/TencentCloud.h>
#include <tencentcloud/core/profile/ClientProfile.h>
#include <tencentcloud/core/profile/HttpProfile.h>
#include <tencentcloud/core/Credential.h>
#include <tencentcloud/vod/v20240718/VodClient.h>
#include <tencentcloud/vod/v20240718/model/CreateStorageCredentialsRequest.h>
#include <tencentcloud/vod/v20240718/model/CreateStorageCredentialsResponse.h>
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

// Constants
const uint64_t APP_ID = 251000000; // Tencent Cloud Account APPID
const uint64_t SUB_APP_ID = 1234567890; // VOD Professional Application APPID
const std::string BUCKET_ID = "auto"; // VOD Professional Bucket ID, 'auto' enables automatic selection
const std::string REGION = "auto"; // VOD Professional Bucket Region, 'auto' enables automatic selection
const std::string OBJECT_KEY = "upload/demo.mp4"; // Storage object key with full path

// Credential structure
struct Credential
{
std::string accessKeyId;
std::string secretAccessKey;
std::string sessionToken;
};

// URL encoding function
std::string UrlEncode(const std::string &value)
{
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;

for (char c : value)
{
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
{
escaped << c;
}
else
{
escaped << std::uppercase;
escaped << '%' << std::setw(2) << int((unsigned char)c);
escaped << std::nouppercase;
}
}

return escaped.str();
}

// Obtain temporary storage credentials
Credential GetCredential()
{
// Initialize Tencent Cloud SDK
TencentCloud::InitAPI();

// Create VOD client
TencentCloud::Credential credential("SecretId", "SecretKey"); // Enter your Tencent Cloud SecretId and SecretKey
TencentCloud::HttpProfile httpProfile;
TencentCloud::ClientProfile clientProfile;
clientProfile.SetHttpProfile(httpProfile);

TencentCloud::Vod::V20240718::VodClient client(credential, "ap-guangzhou", clientProfile);

// Build policy
json policy_json = {
{"statement", {{{"action", {"name/vod:PutObject", "name/vod:ListParts", "name/vod:PostObject",
"name/vod:CreateMultipartUpload", "name/vod:UploadPart",
"name/vod:CompleteMultipartUpload", "name/vod:AbortMultipartUpload",
"name/vod:ListMultipartUploads"}},
{"effect", "allow"},
{"resource", {"qcs::vod:" + REGION + ":uid/" + std::to_string(APP_ID) +
":prefix//" + std::to_string(SUB_APP_ID) + "/" + BUCKET_ID + "/" + OBJECT_KEY}}}}},
{"version", "2.0"}};
std::string policy = policy_json.dump();

// Create credential request
TencentCloud::Vod::V20240718::Model::CreateStorageCredentialsRequest req;
req.SetSubAppId(SUB_APP_ID);
req.SetPolicy(UrlEncode(policy));

// Send request
auto outcome = client.CreateStorageCredentials(req);
if (!outcome.IsSuccess())
{
std::cerr << "Failed to obtain storage credentials: " << outcome.GetError().GetErrorMessage() << std::endl;
TencentCloud::ShutdownAPI();
exit(1);
}

// Extract credentials
auto response = outcome.GetResult();
auto creds = response.GetCredentials();

Credential result;
result.accessKeyId = creds.GetAccessKeyId();
result.secretAccessKey = creds.GetSecretAccessKey();
result.sessionToken = creds.GetSessionToken();

// Clean up Tencent Cloud SDK
TencentCloud::ShutdownAPI();

return result;
}
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import urllib.parse
from typing import NamedTuple

from tencentcloud.common import credential
from tencentcloud.common.profile import client_profile
from tencentcloud.vod.v20240718 import vod_client, models

# Constants
APP_ID = 251000000 # Tencent Cloud account APPID
SUB_APP_ID = 1234567890 # VOD Professional Application APPID
BUCKET_ID = "auto" # VOD Professional Bucket ID, 'auto' enables automatic bucket selection
OBJECT_KEY = "upload/demo.mp4" # File KEY for storage after upload
REGION = "auto" # Region setting, 'auto' enables automatic region selection

class Credential(NamedTuple):
"""Temporary credentials for storage access"""
access_key_id: str
secret_access_key: str
session_token: str

def get_credential() -> Credential:
"""Obtain credentials for VOD storage access"""
# 1. Initialize Tencent Cloud API client
cred = credential.Credential(
"SecretId", # Tencent Cloud account SecretId
"SecretKey", # Tencent Cloud account SecretKey
)
prof = client_profile.ClientProfile()
vod_cli = vod_client.VodClient(cred, "ap-guangzhou", prof)

# 2. Prepare policy for requesting credentials
policy = {
"statement": [
{
"action": [
"name/vod:PutObject",
"name/vod:ListParts",
"name/vod:PostObject",
"name/vod:CreateMultipartUpload",
"name/vod:UploadPart",
"name/vod:CompleteMultipartUpload",
"name/vod:AbortMultipartUpload",
"name/vod:ListMultipartUploads",
],
"effect": "allow",
"resource": [
f"qcs::vod:{REGION}:uid/{APP_ID}:prefix//{SUB_APP_ID}/{BUCKET_ID}/{OBJECT_KEY}"
],
}
],
"version": "2.0",
}

# 3. Create credential request
req = models.CreateStorageCredentialsRequest()
req.SubAppId = SUB_APP_ID
req.Policy = urllib.parse.quote(json.dumps(policy))

# 4. Request temporary storage credentials
resp = vod_cli.CreateStorageCredentials(req)
creds = resp.Credentials
return Credential(
access_key_id=creds.AccessKeyId,
secret_access_key=creds.SecretAccessKey,
session_token=creds.SessionToken,
)
Upload Files
Common languages initialize the S3 client and upload files as shown below:
GO
Java
C++
Python
// Package main
// This example is implemented using AWS SDK for Go v2 service/s3 v1.72.3.
// AWS SDK for Go v2 service/s3 v1.73.0 and later require disabling S3's default integrity protection.
// Reference: https://github.com/aws/aws-sdk-go-v2/discussions/2960
package main

import (
"context"
"errors"
"fmt"
"log"
"net/url"
"os"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
smep "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/logging"
)

type customEndpointResolverV2 struct {
}

// ResolveEndpoint custom endpoint
func (r *customEndpointResolverV2) ResolveEndpoint(ctx context.Context,
params s3.EndpointParameters) (smep.Endpoint, error) {
if params.Bucket == nil || params.Region == nil {
return smep.Endpoint{}, errors.New("invalid endpoint param")
}
return smep.Endpoint{
URI: url.URL{
Scheme: "https",
Host: fmt.Sprintf(
"%d.vodpro-upload.com",
subAppId, // Sub-account Id
),
},
}, nil
}

func main() {
// 1. Obtain credentials
cred, err := getCredential(context.Background())
if err != nil {
log.Fatalf("get credential fail: %v", err)
return
}

// 2. Upload file using credentials
// 2.1 Create s3 client
s3cli := s3.New(s3.Options{
Credentials: credentials.NewStaticCredentialsProvider(
cred.AccessKeyId,
cred.SecretAccessKey,
cred.SessionToken,
),
EndpointResolverV2: new(customEndpointResolverV2), // Custom endpoint
UsePathStyle: true, // Application-level domain must explicitly enable path style requests
Logger: logging.NewStandardLogger(os.Stdout), // Log to stdout
ClientLogMode: aws.LogRequest | aws.LogResponse, // Log request and response headers
Region: "auto", // Must be set to "auto"
})

// 2.2 Open local file
file, err := os.Open("demo.mp4") // Local file path
if err != nil {
log.Fatalf("failed to open file: %v", err)
return
}
defer file.Close()

// 2.3 Upload file to S3
// 2.3.1 Create uploader
uploader := manager.NewUploader(s3cli, func(u *manager.Uploader) {
u.PartSize = 10 * 1024 * 1024 // Set part size to 10MB
u.Concurrency = 5 // Set concurrent upload parts
})
// Application-level upload path is bucketId/fileKey
// S3 SDK Uploader doesn't support path style mode, need to concatenate as upload key
path, err := url.JoinPath(bucketId, fileKey)
if err != nil {
log.Fatalf("failed to join path: %v", err)
return
}
// 2.3.2 Upload file
result, err := uploader.Upload(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String(bucketId), // Set Bucket to bucket ID in VOD Professional Edition
// File path in bucket
// Application-level upload path is bucketId/fileKey
// S3 SDK Uploader doesn't support path style mode, need to concatenate as upload key
Key: aws.String(path),
Body: file,
})

if err != nil {
log.Fatalf("failed to upload file: %v", err)
return
}
log.Printf("etag: %s", *result.ETag) // Get uploaded file etag
}
// This example is implemented using AWS SDK for Java v2 service/s3 v2.31.35.
// AWS SDK for Java 2.30.0 and later require disabling S3's default integrity protection.
// Reference: https://github.com/aws/aws-sdk-java-v2/issues/5801
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.core.checksums.RequestChecksumCalculation;
import software.amazon.awssdk.core.checksums.ResponseChecksumValidation;

import java.io.File;
import java.net.URI;
import java.util.concurrent.CompletableFuture;

public class Main {
public static void main(String[] args) {
S3AsyncClient s3AsyncClient = null;
S3TransferManager transferManager = null;

try {
// 1. Obtain credentials
CredentialHelper.Cred cred = CredentialHelper.getCredential();
System.out.println("Obtained credentials, AccessKeyId: " + cred.getAccessKeyId());

// 2. Create session credentials (with temporary token)
AwsSessionCredentials sessionCredentials = AwsSessionCredentials.create(
cred.getAccessKeyId(), // Temporary credential AccessKeyId
cred.getSecretAccessKey(), // Temporary credential SecretAccessKey
cred.getSessionToken() // Temporary credential SessionToken
);

long subAppId = 1234567890; // VOD Professional Edition application APPID
String bucketId = "auto"; // VOD Professional Edition bucket ID, "auto" means automatically select nearby bucket
String filePath = "demo.mp4"; // Local file path
String key = "upload/demo.mp4"; // File KEY to apply permissions for
String endpointUrl = String.format("https://%d.vodpro-upload.com", subAppId); // Application-level preset domain endpoint

// 3. Build S3 async client with custom endpoint
s3AsyncClient = S3AsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(sessionCredentials)) // Set credentials provider
.endpointOverride(URI.create(endpointUrl)) // Set endpoint
.region(Region.of("auto")) // Must be set to "auto"
.httpClient(NettyNioAsyncHttpClient.builder().build()) // Set HTTP client
.serviceConfiguration(S3Configuration.builder()
.pathStyleAccessEnabled(true) // Set path style access, application level must explicitly use PathStyle mode
.build())
.requestChecksumCalculation(RequestChecksumCalculation.WHEN_REQUIRED)
.responseChecksumValidation(ResponseChecksumValidation.WHEN_REQUIRED)
.build();

// 4. Create S3TransferManager with S3 async client
transferManager = S3TransferManager.builder()
.s3Client(s3AsyncClient)
.build();

// 5. Prepare file for upload
File fileToUpload = new File(filePath);
if (!fileToUpload.exists()) {
throw new RuntimeException("File not found: " + filePath);
}

// 6. Create upload request with transfer listener for progress tracking
UploadFileRequest uploadRequest = UploadFileRequest.builder()
.putObjectRequest(builder -> builder
.bucket(bucketId)
.key(key))
.addTransferListener(LoggingTransferListener.create())
.source(fileToUpload)
.build();

// 7. Start upload
System.out.println("Starting file upload...");
CompletableFuture<Void> future = transferManager.uploadFile(uploadRequest)
.completionFuture()
.thenAccept(response -> {
System.out.println("Upload successful! ETag: " + response.response().eTag());
});

// 8. Wait for upload to complete
future.join();

System.out.println("Upload task completed");
} catch (Exception e) {
System.err.println("Upload failed: " + e.getMessage());
e.printStackTrace();
} finally {
// Release resources
try {
if (transferManager != null) {
transferManager.close();
}
if (s3AsyncClient != null) {
s3AsyncClient.close();
}
System.out.println("Resources released");
} catch (Exception e) {
System.err.println("Error closing resources: " + e.getMessage());
}
}
}
}
// This example is implemented using AWS SDK for C++ v1.11.560.
// AWS SDK for C++ v1.11.486 and later require disabling S3's default integrity protection.
// Reference: https://github.com/aws/aws-sdk-cpp/issues/3253
#include <aws/core/Aws.h>
#include <aws/core/auth/AWSCredentials.h>
#include <aws/core/client/ClientConfiguration.h>
#include <aws/s3/S3Client.h>
#include <aws/transfer/TransferManager.h>
#include <iostream>
#include <string>

// Reference credential struct from get_cred.cpp
struct Credential
{
std::string accessKeyId;
std::string secretAccessKey;
std::string sessionToken;
};

// Reference function from get_cred.cpp
extern Credential GetCredential();

int main()
{
// AWS SDK initialization
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Info;
Aws::InitAPI(options);

{
// Get credentials
std::cout << "Getting credentials..." << std::endl;
Credential cred = GetCredential();
std::cout << "Successfully obtained credentials, access key Id: " << cred.accessKeyId << std::endl;
// Define constants
const uint64_t subAppId = 1234567890; // VOD Professional Edition application SubAppId
const Aws::String bucketId = "auto"; // VOD Professional Edition bucket ID, "auto" means automatically select nearby bucket
const Aws::String keyName = "upload/demo.mp4"; // File path in bucket, including full path and filename
const Aws::String filePath = "demo.mp4"; // Local file path

// Configure client
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = "auto"; // Must be set to "auto"
clientConfig.scheme = Aws::Http::Scheme::HTTPS; // Use HTTPS protocol
clientConfig.enableEndpointDiscovery = false; // Disable endpoint discovery
clientConfig.verifySSL = true; // Enable SSL certificate verification
clientConfig.endpointOverride = std::to_string(subAppId) + ".vodpro-upload.com"; // Application-level preset domain
// Disable integrity check
clientConfig.checksumConfig.requestChecksumCalculation = Aws::Client::RequestChecksumCalculation::WHEN_REQUIRED;
clientConfig.checksumConfig.responseChecksumValidation = Aws::Client::ResponseChecksumValidation::WHEN_REQUIRED;

// Set authentication information (using credentials)
Aws::Auth::AWSCredentials credentials(
cred.accessKeyId.c_str(),
cred.secretAccessKey.c_str(),
cred.sessionToken.c_str());

// Create S3 client
auto s3Client = Aws::MakeShared<Aws::S3::S3Client>(
"S3Client",
credentials,
clientConfig,
Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never, // Disable payload signing
false // Application-level domain requires explicit PathStyle format
);

// Create thread pool executor
auto executor = Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>("executor", 10);

// Configure TransferManager
Aws::Transfer::TransferManagerConfiguration transferConfig(executor.get());
transferConfig.s3Client = s3Client;

// Set part size to 10MB
transferConfig.bufferSize = 10 * 1024 * 1024;

// Create TransferManager
auto transferManager = Aws::Transfer::TransferManager::Create(transferConfig);

std::cout << "Starting file upload: " << filePath << " to " << bucketId << "/" << keyName << std::endl;

// Perform upload
auto uploadHandle = transferManager->UploadFile(
filePath, // Local file path
bucketId, // Bucket ID
keyName, // Object key (storage path)
"application/octet-stream", // Content type
Aws::Map<Aws::String, Aws::String>() // Metadata
);

// Wait for upload to complete
uploadHandle->WaitUntilFinished();

// Check upload status
if (uploadHandle->GetStatus() == Aws::Transfer::TransferStatus::COMPLETED)
{
std::cout << "File upload completed successfully!" << std::endl;
}
else
{
auto lastError = uploadHandle->GetLastError();
std::cerr << "File upload failed: " << lastError.GetMessage() << std::endl;
}
}

// Clean up SDK resources
Aws::ShutdownAPI(options);
return 0;
}
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
This example is implemented using AWS SDK for Python v1.38.7.
Boto3 AWS SDK for Python v1.36.0 and later require disabling S3's default integrity protection.
Reference: https://github.com/boto/boto3/issues/4392
"""

import boto3
from botocore.config import Config
from botocore.exceptions import ClientError

from get_cred import get_credential, SUB_APP_ID, BUCKET_ID, OBJECT_KEY

# Constant definitions
FILE_PATH = "demo.mp4"

try:
# 1. Obtain credentials
cred = get_credential()

# 2. Create S3 client
s3_client = boto3.client(
"s3",
aws_access_key_id=cred.access_key_id, # Temporary credential AccessKeyId
aws_secret_access_key=cred.secret_access_key, # Temporary credential SecretAccessKey
aws_session_token=cred.session_token, # Temporary credential SessionToken
endpoint_url=f"https://{SUB_APP_ID}.vodpro-upload.com", # Application-level preset upload domain
region_name="auto", # Must be set to "auto"
config=Config(
s3={"addressing_style": "path"}, # Use path-style
request_checksum_calculation="when_required", # Boto3 v1.36.0+ require disabling default integrity protection
response_checksum_validation="when_required", # Boto3 v1.36.0+ require disabling default integrity protection
),
)

# 3. Upload file
response = s3_client.upload_file(
Bucket=BUCKET_ID, # Fill in bucket ID in VOD Professional Edition
Key=OBJECT_KEY, # File path in bucket
Filename=FILE_PATH, # Local file path
)
print(response)
except ClientError as e:
print(f"Error: {e}")
Note:
When using AWS SDK, confirm data integrity protection features.
When using application-level upload acceleration domains, the path must be in VirtualStyle format.


Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback