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

Torch Object Storage

Copy page
Download PDF
Upload Object
Resumable Transfer (Harmony SDK)
Copy page
Download PDF
Resumable Transfer (Harmony SDK)
When uploading files to TOS using the resumable upload method, you can configure parameters such as part size, concurrency for uploading parts, client-side rate limiting during upload, and event callback functions. During the upload process, if a network anomaly or program crash causes the file upload to fail, the system will resume uploading the incomplete portion from the last recorded breakpoint. During the upload process, you can cancel the object upload by invoking the Cancel method of the passed-in CancelHook.​
Precautions​
  • When uploading an object, the object name must comply with specific requirements. For detailed information, please refer to the Object Naming Specification.​
  • TOS is a distributed object storage product designed for large-scale storage, with internal partitions that store object index data. To maximize the throughput of uploading and downloading objects and reduce the likelihood of hotspot partitions, please avoid naming objects in lexicographical order. For more details, see Performance Optimization.​
  • If an object with the same name already exists in the bucket, the new object will overwrite the existing one. If versioning is enabled for your bucket, the original object will be retained, and a new version number will be generated to identify the newly uploaded object.​
  • The SDK records the upload status information in the Checkpoint file, so the program must have write permissions for the Checkpoint file.​
  • When using resumable upload, the file upload progress information is recorded in the Checkpoint file. If a chunk fails to upload during the process, retrying the upload will resume from the point recorded in the Checkpoint file. After the upload is complete, the Checkpoint file will be deleted.​
  • If the local file is modified during the upload process, all segments will be re-uploaded.​
Sample Code​
Upload File​
The following code is used to upload files using a resumable upload method.​
​
/*​
* Copyright (c) 2024 Beijing Volcano Engine Technology Ltd and/or its affiliates​
* SPDX-License-Identifier: MIT​
*/​
​
import { TosClient, TosClientError, TosServerError } from '@volcengine/tos_harmonyos_sdk';​
​
​
const client = new TosClient({​
accessKeyId: "Provide your ak",​
accessKeySecret: "Provide your sk",​
securityToken: 'Provide your securityToken',​
region: "Provide your region", ​
endpoint: "Provide your endpoint", ​
});​
​
function handleError(error: Error) {​
if (error instanceof TosClientError) {​
console.log('Client Err Msg:', error.message);​
console.log('Client Err Stack:', error.stack);​
} else if (error instanceof TosServerError) {​
console.log('Request ID:', error.RequestID);​
console.log('Response Status Code:', error.StatusCode);​
console.log('Response Header:', error.Headers);​
console.log('Response Err Code:', error.Code);​
console.log('Response Err Msg:', error.Message);​
} else {​
console.log('unexpected exception, message: ', error);​
}​
}​
​
async function main() {​
try {​
const bucketName = 'harmony-sdk-test-bucket';​
const objectName = 'example_dir/example.txt';​
const filePath = './example_dir/multipartExample';​
const checkpointFile = './example_dir/example.checkpoint';​
​
await client.uploadFile({​
Bucket: bucketName,​
Key: objectName,​
​
FilePath: filePath,​
​
TaskNum: 1,​
​
PartSize: 10 * 1024 * 1024,​
​
CheckpointFile: checkpointFile,​
​
EnableCheckpoint: true,​
});​
} catch (error) {​
handleError(error);​
}​
}​
​
main();​
​
Configure Progress Bar​
During resumable upload, upload progress can be received via the DataTransferStatusChange parameter. A code example is provided below.​
​
import { DataTransferType, TosClient, TosClientError, TosServerError } from '@volcengine/tos_harmonyos_sdk';​
​
​
const client = new TosClient({​
accessKeyId: "Provide your ak",​
accessKeySecret: "Provide your sk",​
securityToken: 'Provide your securityToken',​
region: "Provide your region", ​
endpoint: "Provide your endpoint", ​
});​
​
function handleError(error: Error) {​
if (error instanceof TosClientError) {​
console.log('Client Err Msg:', error.message);​
console.log('Client Err Stack:', error.stack);​
} else if (error instanceof TosServerError) {​
console.log('Request ID:', error.RequestID);​
console.log('Response Status Code:', error.StatusCode);​
console.log('Response Header:', error.Headers);​
console.log('Response Err Code:', error.Code);​
console.log('Response Err Msg:', error.Message);​
} else {​
console.log('unexpected exception, message: ', error);​
}​
}​
​
async function main() {​
try {​
const bucketName = 'harmony-sdk-test-bucket';​
const objectName = 'example_dir/example.txt';​
const filePath = './example_dir/multipartExample';​
const checkpointFile = './example_dir/example.checkpoint';​
​
await client.uploadFile({​
Bucket: bucketName,​
Key: objectName,​
FilePath: filePath,​
​
CheckpointFile: checkpointFile,​
​
EnableCheckpoint: true,​
DataTransferListener:{​
DataTransferStatusChange(event){​
if (event.Type === DataTransferType.Started) {​
console.log('Data Transfer Started');​
} else if (event.Type === DataTransferType.RW) {​
const percent = ((event.ConsumedBytes / event.TotalBytes) * 100).toFixed(2);​
console.log(`Once Read:${event.RWOnceBytes},ConsumerBytes/TotalBytes: ${event.ConsumedBytes}/${event.TotalBytes},${percent}%`);​
} else if (event.Type === DataTransferType.Succeed) {​
const percent = ((event.ConsumedBytes / event.TotalBytes) * 100).toFixed(2);​
console.log(`Data Transfer Succeed, ConsumerBytes/TotalBytes:${event.ConsumedBytes}/${event.TotalBytes},${percent}%`);​
} else if (event.Type === DataTransferType.Failed) {​
console.log('Data Transfer Failed');​
}​
}​
}​
});​
} catch (error) {​
handleError(error);​
}​
}​
​
main();​
​
Handling Event Callbacks​
The following code is used to customize the callback function for resumable upload.​
​
import { TosClient, TosClientError, TosServerError, UploadEventType } from '@volcengine/tos_harmonyos_sdk';​
​
​
const client = new TosClient({​
accessKeyId: "Provide your ak",​
accessKeySecret: "Provide your sk",​
securityToken: 'Provide your securityToken',​
region: "Provide your region", ​
endpoint: "Provide your endpoint", ​
});​
​
function handleError(error: Error) {​
if (error instanceof TosClientError) {​
console.log('Client Err Msg:', error.message);​
console.log('Client Err Stack:', error.stack);​
} else if (error instanceof TosServerError) {​
console.log('Request ID:', error.RequestID);​
console.log('Response Status Code:', error.StatusCode);​
console.log('Response Header:', error.Headers);​
console.log('Response Err Code:', error.Code);​
console.log('Response Err Msg:', error.Message);​
} else {​
console.log('unexpected exception, message: ', error);​
}​
}​
​
async function main() {​
try {​
const bucketName = 'harmony-sdk-test-bucket';​
const objectName = 'example_dir/example.txt';​
const filePath = './example_dir/multipartExample';​
const checkpointFile = './example_dir/example.checkpoint';​
​
await client.uploadFile({​
Bucket: bucketName,​
Key: objectName,​
​
FilePath: filePath,​
​
CheckpointFile: checkpointFile,​
​
EnableCheckpoint: true,​
UploadEventListener:{​
EventChange(event){​
switch (event.Type) {​
case UploadEventType.CreateMultipartUploadSucceed: {​
console.log(`Upload to ${event.Bucket} ${event.Key} create multipart upload success, upload id:${event.UploadID}`);​
break;​
}​
case UploadEventType.CreateMultipartUploadFailed: {​
console.log(`Upload to ${event.Bucket} ${event.Key} create multipart upload fail, upload id:${event.UploadID}`);​
break;​
}​
case UploadEventType.UploadPartSucceed: {​
console.log(`Upload to${event.Bucket} ${event.Key} part success, UploadPartInfo:%o`, event.UploadPartInfo);​
break;​
}​
case UploadEventType.UploadPartAborted: {​
console.log(`Upload to ${event.Bucket} ${event.Key} part aborted, upload id:${event.UploadID}`);​
break;​
}​
case UploadEventType.UploadPartFailed: {​
console.log(`Upload to ${event.Bucket} ${event.Key} part fail, upload id:${event.UploadID}`);​
break;​
}​
case UploadEventType.CompleteMultipartUploadSucceed: {​
console.log(`Upload to ${event.Bucket} ${event.Key} success, upload id:${event.UploadID}`);​
break;​
}​
case UploadEventType.CompleteMultipartUploadFailed: {​
console.log(`Upload to ${event.Bucket} ${event.Key} fail, upload id:${event.UploadID}, err: %o`, event.Err);​
break;​
}​
}​
}​
}​
});​
} catch (error) {​
handleError(error);​
}​
}​
​
main();​
​
Cancellation Mechanism​
The following code is used to cancel an ongoing resumable upload task during runtime.​
​
import { TosClient, TosClientError, TosServerError, UploadEventType, CancelHook } from '@volcengine/tos_harmonyos_sdk';​
​
​
const client = new TosClient({​
accessKeyId: "Provide your ak",​
accessKeySecret: "Provide your sk",​
securityToken: 'Provide your securityToken',​
region: "Provide your region", ​
endpoint: "Provide your endpoint", ​
});​
​
function handleError(error: Error) {​
if (error instanceof TosClientError) {​
console.log('Client Err Msg:', error.message);​
console.log('Client Err Stack:', error.stack);​
} else if (error instanceof TosServerError) {​
console.log('Request ID:', error.RequestID);​
console.log('Response Status Code:', error.StatusCode);​
console.log('Response Header:', error.Headers);​
console.log('Response Err Code:', error.Code);​
console.log('Response Err Msg:', error.Message);​
} else {​
console.log('unexpected exception, message: ', error);​
}​
}​
​
async function main() {​
const cancelHook = new CancelHook();​
try {​
const bucketName = 'harmony-sdk-test-bucket';​
const objectName = 'example_dir/example.txt';​
const filePath = './example_dir/multipartExample';​
const checkpointFile = './example_dir/example.checkpoint'​
​
client.uploadFile({​
Bucket: bucketName,​
Key: objectName,​
​
FilePath: filePath,​
CancelHook: cancelHook,​
​
CheckpointFile: checkpointFile,​
​
EnableCheckpoint: true,​
});​
​
​
setTimeout(() => {​
cancelHook.Cancel();​
}, 1000)​
​
} catch (error) {​
handleError(error);​
}​
}​
​
main();​
​
​
Last updated: 2025.09.26 19:05:17