You need to enable JavaScript to run this app.
Torch Object Storage

Torch Object Storage

Copy page
Download PDF
Best Practices
Accessing TOS with AWS S3 SDK
Copy page
Download PDF
Accessing TOS with AWS S3 SDK
This topic will help you quickly and correctly configure the AWS S3 SDK for various major programming languages so you can access and manage TOS resources.​
Overview​
TOS provides Amazon S3-compatible APIs. This allows you to easily access and manage your storage resources on TOS with a simple configuration using the well-established, feature-rich AWS S3 SDKs.​
  • Unified technology stack: In multi-cloud environments, you can use the same AWS S3 SDK to manage storage services from different cloud providers, simplifying development and maintenance.​
  • Smooth migration: Applications migrating from AWS S3 or other S3-compatible storage to TOS require almost no code changes — just update the client configuration.​
  • Mature ecosystem: You can leverage the stable and efficient development experience of the AWS S3 SDK, along with an abundance of community examples and solutions.​
Prerequisites​
  • You have created an FNS bucket. For more information on bucket types and how to create a bucket, see Bucket type and Creating buckets.​
  • To ensure secure connections, we recommend using AWS Signature Version 4 (s3v4) with AWS S3 SDKs.​
  • TOS S3-compatible domains only support virtual-hosted-style addressing. Path-style addressing is not supported. Therefore, when configuring the SDK, either explicitly specify virtual-hosted style or ensure that it is the default setting. If the SDK defaults to path-style addressing, disable it. This is critical for a successful connection.​
Configuration parameters​
  • Region: The region where your TOS bucket is located, for example, cn-beijing. For more information, see Regions and endpoints.​
  • Access Key: A pair of access key ID (AK) and secret access key (SK) that serves as credentials for accessing the TOS API. For more information on creating and managing access keys, see API Access Key.​
Configuring access credentials​
Before initializing the SDK, you must first set up long-term access credentials. This process differs depending on the operating system.​
​
macOS
Linux
Windows
​
  1. Open Terminal and run this command to open the file.​
  • ​
    nano ~/.bash_profile​
    ​
  1. Add your access key ID and secret access key at the end of the file.​
  • ​
    export TOS_ACCESS_KEY=AKTP**********​
    export TOS_SECRET_KEY=T1dJ**********​
    ​
  1. Save the file and exit.​
  1. Run this command to apply the configuration.​
  • ​
    source ~/.bash_profile​
    ​
  1. Run this command to verify the configuration.​
  • ​
    echo $TOS_ACCESS_KEY​
    echo $TOS_SECRET_KEY​
    ​
  • The following output confirms a successful configuration.​
  • ​
    AKTP**********​
    T1dJ**********​
    ​
​
​
Examples​
​
Java
Python
Go
C++
JavaScript(Node.js)
PHP
Rust
C#(.NET)
​
We recommend using the AWS SDK for Java v2, which provides a more modern API and better performance.​
Environment​
Make sure your development environment has JDK 8 or later installed.​
Adding dependencies​
Maven​
Add the following dependency to your pom.xml file:​
​
<dependency>​
<groupId>software.amazon.awssdk</groupId>​
<artifactId>s3</artifactId>​
<version>2.25.27</version>​
</dependency>​
​
Gradle​
Add the following dependency to your build.gradle file:​
​
implementation 'software.amazon.awssdk:s3:2.25.27'​
​
Code example​
The following example illustrates how to initialize the S3Client and perform basic operations.​
​
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;​
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;​
import software.amazon.awssdk.core.ResponseBytes;​
import software.amazon.awssdk.core.sync.RequestBody;​
import software.amazon.awssdk.core.sync.ResponseTransformer;​
import software.amazon.awssdk.regions.Region;​
import software.amazon.awssdk.services.s3.S3Client;​
import software.amazon.awssdk.services.s3.model.*;​
​
import java.io.IOException;​
import java.net.URI;​
import java.nio.file.Files;​
import java.nio.file.Paths;​
​
public class TosS3JavaBestPractice {​
​
public static void main(String[] args) {​
// 1. Configure authentication information and endpoint​
final String endpoint = "https://tos-s3-cn-beijing.volces.com";​
final String region = "cn-beijing";​
final String accessKey = System.getenv("VOLCENGINE_ACCESS_KEY_ID");​
final String secretKey = System.getenv("VOLCENGINE_SECRET_ACCESS_KEY");​
​
// 2. Initialize the S3Client​
// Note: The AWS SDK for Java v2 uses virtual-hosted style by default​
// To disable path-style explicitly (which is required by some legacy versions or special configurations), use .forcePathStyle(false)​
S3Client s3Client = S3Client.builder()​
.endpointOverride(URI.create(endpoint))​
.region(Region.of(region))​
.credentialsProvider(StaticCredentialsProvider.create(​
AwsBasicCredentials.create(accessKey, secretKey)))​
.build();​
​
String bucketName = "your-unique-bucket-name-" + System.currentTimeMillis();​
String objectKey = "my-object-key";​
String localFilePath = "local-file.txt";​
String downloadFilePath = "downloaded-file.txt";​
​
try {​
// Prepare a local file​
Files.write(Paths.get(localFilePath), "Hello, Volcengine TOS!".getBytes());​
​
// 3. Create a bucket​
System.out.println("Creating bucket: " + bucketName);​
s3Client.createBucket(CreateBucketRequest.builder().bucket(bucketName).build());​
System.out.println("Bucket created successfully.");​
​
// 4. Upload an object​
System.out.println("Uploading object to " + bucketName);​
s3Client.putObject(PutObjectRequest.builder()​
.bucket(bucketName)​
.key(objectKey)​
.build(), RequestBody.fromFile(Paths.get(localFilePath)));​
System.out.println("Object uploaded successfully.");​
​
// 5. List objects​
System.out.println("Listing objects in bucket: " + bucketName);​
ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(ListObjectsV2Request.builder()​
.bucket(bucketName).build());​
for (S3Object s3Object : listObjectsV2Response.contents()) {​
System.out.println("- " + s3Object.key());​
}​
​
// 6. Download an object​
System.out.println("Downloading object: " + objectKey);​
ResponseBytes<GetObjectResponse> objectBytes = s3Client.getObject(​
GetObjectRequest.builder().bucket(bucketName).key(objectKey).build(),​
ResponseTransformer.toBytes());​
Files.write(Paths.get(downloadFilePath), objectBytes.asByteArray());​
System.out.println("Object downloaded successfully to " + downloadFilePath);​
​
// 7. Delete an object​
System.out.println("Deleting object: " + objectKey);​
s3Client.deleteObject(DeleteObjectRequest.builder().bucket(bucketName).key(objectKey).build());​
System.out.println("Object deleted successfully.");​
​
// 8. Delete a bucket​
System.out.println("Deleting bucket: " + bucketName);​
s3Client.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build());​
System.out.println("Bucket deleted successfully.");​
​
} catch (S3Exception | IOException e) {​
System.err.println("Error: " + e.getMessage());​
e.printStackTrace();​
} finally {​
// Remove a local file​
try {​
Files.deleteIfExists(Paths.get(localFilePath));​
Files.deleteIfExists(Paths.get(downloadFilePath));​
} catch (IOException ex) {​
System.err.println("Failed to clean up local files: " + ex.getMessage());​
}​
s3Client.close();​
}​
}​
}​
​
​
FAQ​
  1. LocationConstraint in CreateBucket​
  • The S3 API requires the LocationConstraint parameter when creating a bucket in a region other than US East (N. Virginia), us-east-1. However, TOS S3-compatible APIs do not currently require this parameter, even in regions such as cn-beijing. Therefore, you can omit this configuration. If the SDK asks you to provide it, though, simply enter the same value for region.​
  1. Certificate validation error​
  • In corporate intranet or proxy environments, SSL certificate validation may occasionally be intercepted. Make sure that your development environment trusts certificates for the *.volces.com domain.​
  • Some SDKs, such as the Python boto3 SDK, allow you to disable SSL certificate validation for debugging purposes using the verify=False parameter. However, doing so poses a security risk. We strongly recommend properly resolving this issue in production environments by configuring system or CA certificate trust chains.​
  1. Signature version mismatch​
  • If you encounter signature-related errors when calling APIs, check your SDK initialization configuration. Make sure you have specified the AWS Signature Version 4 algorithm (s3v4) explicitly. TOS S3-compatible APIs depend heavily on this signature version.​
  1. Incorrect virtual-hosted style configuration​
  • This is the most common configuration mistake when integrating with TOS. TOS S3-compatible domains do not support path-style addressing (e.g., https://tos-s3-cn-beijing.volces.com/bucket-name). All requests must use virtual-hosted-style addressing (e.g., https://bucket-name.tos-s3-cn-beijing.volces.com). Carefully check the addressing mode of the SDK you are using.​
Last updated: 2026.08.25 10:39:45