Skip to main content

Cloud storage

uploadFile

1. API Description

API feature: upload files

API Declaration:

2.x version

uploadFile(options)

1.x version

uploadFile(localPath: string, cloudPath: string)

Note: v2.x is incompatible with v1.x.

2. Input Parameters

FieldRequiredTypeDescription
localPathYesStringLocal file path. It is recommended to pass an absolute path.
cloudPathRequiredStringCloud file path: dir/data.txt
onProgressRequiredFunctionUpload progress callback function

Note: When localPath is a folder, the SDK will attempt to find a file with the same name as the file in cloudPath within this folder (first-level directory, no deep traversal). For example, if cloudPath is dir/data.txt, it will look for 'data.txt'.

3. Return Results

N/A

4. Sample Code

import path from "path";

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
await storage.uploadFile({
localPath: path.resolve("./data.txt"),
cloudPath: "files/data.txt",
onProgress: (data) => {},
});
}

test();

uploadDirectory

1. API Description

API feature: Uploading folders

API Declaration:

2.x version

uploadDirectory(options)

1.x version

uploadDirectory(source: string, cloudPath: string)

Note: v2.x is incompatible with v1.x.

This API traverses all files in the target folder and uploads them while preserving the folder structure.

2. Input Parameters

FieldRequiredTypeDescription
localPathRequiredStringLocal folder path
cloudPathRequiredStringCloud folder path
onProgressRequiredFunctionUpload progress callback function

3. Return Results

N/A

4. Sample Code

import path from "path";

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
await storage.uploadDirectory({
localPath: path.resolve("./files"),
cloudPath: "",
onProgress: (data) => {},
});
}

test();

downloadFile

1. API Description

API feature: download files

API Declaration:

2.x version

downloadFile(options)

1.x version

downloadFile(cloudPath: string, localPath)

Note: v2.x is incompatible with v1.x.

2. Input Parameters

FieldRequiredTypeDescription
cloudPathRequiredStringCloud file path: dir/data.txt
localPathRequiredStringLocal file storage path; the file name must be specified

3. Return Results

None (undefined)

4. Sample Code

import path from "path";

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
await storage.downloadFile({
cloudPath: "files/data.txt",
localPath: path.resolve("./data.txt"),
});
}

test();

downloadDirectory

1. API Description

API feature: download folder

API Declaration:

2.x version

downloadDirectory(options)

1.x version

downloadDirectory(cloudPath: string, localPath: string)

Note: v2.x is incompatible with v1.x.

2. Input Parameters

FieldRequiredTypeDescription
cloudPathRequiredStringCloud folder
localPathRequiredStringLocal file storage path; the file name must be specified

3. Return Results

N/A

4. Sample Code

import path from "path";

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
await storage.downloadDirectory({
cloudPath: "files/music",
localPath: path.resolve("./music"),
});
}

test();

NOTE:

  • This operation traverses all files in the folder. If the number of files is too large, it may cause the execution to fail.
  • When cloudPath does not exist, the SDK will not download the file and will not throw an error.

listDirectoryFiles

1. API Description

API feature: List all files in the folder

API declaration: listDirectoryFiles(cloudPath: string): Promise<IListFileInfo[]>

2. Input Parameters

FieldRequiredTypeDescription
cloudPathRequiredStringCloud folder path: dir/data/

3. Return Results

FieldRequiredTypeDescription
-RequiredArray<FileItem>File array

FileItem

FieldTypeDescription
KeyStringObject Key
LastModifiedStringLast modified time of the object, in ISO8601 format, such as 2019-05-24T10:56:40Z date
ETagStringThe entity tag (Entity Tag) of the object, which is an information tag that identifies the content of the object when it is created and can be used to check whether the content of the object has changed
SizeStringObject size, unit: bytes
OwnerStringObject owner information
StorageClassStringCOS storage type: Standard Storage STANDARD

4. Sample Code

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
const res1 = await storage.listDirectoryFiles("dir/data");

const res2 = await storage.listDirectoryFiles("dir/data", 20);

const res3 = await storage.listDirectoryFiles("dir/data", 20, "dir/dat");

for (let item in res1) {
console.log(item);
}
}
test();

getFileInfo

1. API Description

API feature: Obtain file information

API declaration: getFileInfo(cloudPath: string): Promise<IFileInfo>

2. Input Parameters

FieldRequiredTypeDescription
cloudPathRequiredStringCloud file path dir/data.txt

3. Return Results

FieldRequiredTypeDescription
SizeRequiredStringFile size, unit: KB
TypeRequiredStringFile type
DateRequiredStringModification time
ETagYesStringEntity tag of the object (Entity Tag)

4. Sample Code

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
const info = await storage.getFileInfo("files/data.txt");
console.log(info);
}

test();

deleteFile

1. API Description

API feature: Batch delete files

API declaration: deleteFile(cloudPathList: string[])

2. Input Parameters

FieldRequiredTypeDescription
cloudPathListRequiredArray<String>String array consisting of cloud file paths ['dir/data.txt']

3. Return Results

N/A

4. Sample Code

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
await storage.deleteFile(["files/data.txt"]);
}

test();

deleteDirectory

1. API Description

API feature: Delete a folder

API declaration: deleteDirectory(cloudPath: string)

2. Input Parameters

FieldRequiredTypeDescription
cloudPathRequiredStringCloud folder path

Note: When cloudPath does not exist, the SDK will not throw an error.

3. Return Results

N/A

4. Sample Code

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
await storage.deleteDirectory("files/");
}

test();

getTemporaryUrl

1. API Description

API feature: Obtain a temporary download link for a file

API declaration: getTemporaryUrl(fileList: (string | TempUrlInfo)[]):Promise<Array.<FileUrlItem>>

2. Input Parameters

FieldRequiredTypeDescription
fileListRequiredString or Array.<TempUrlInfo>Array of cloud file paths or Array of TempUrlInfo

TempUrlInfo

FieldRequiredTypeDescription
cloudPathRequiredStringCloud file path
maxAgeRequiredNumberValidity period of the temporary download link, unit: seconds

3. Return Results

FieldRequiredTypeDescription
-RequiredArray.<FileUrlItem>List of file download URLs

FileUrlItem

FieldRequiredTypeDescription
fileIdRequiredStringFile Id
urlRequiredStringdownload link

4. Sample Code

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
const urls = await storage.getTemporaryUrl(["files/data.txt"]);

const urls2 = await storage.getTemporaryUrl([
{
cloudPath: "files/data.txt",
maxAge: 86400,
},
]);

for (let item in urls) {
console.log(item.url);
}
}

test();

getStorageAcl

1. API Description

API feature: Obtain file storage permissions

API declaration: getStorageAcl(): Promise<string>

2. Input Parameters

Empty

3. Return Results

FieldRequiredTypeDescription
-RequiredStringPermission type

All permission types:

  • READONLY: Readable by all users, writable only by the creator and administrators.
  • PRIVATE: Readable and writable only by the creator and administrators.
  • ADMINWRITE: Readable by all users, writable only by administrators.
  • ADMINONLY: Readable and writable only by administrators

4. Sample Code

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
const acl = await storage.getStorageAcl();
console.log(acl);
}

test();

setStorageAcl

1. API Description

API feature: Set file storage permissions

API declaration: setStorageAcl(acl: string):Promise<Object>

2. Input Parameters

FieldRequiredTypeDescription
aclYesStringFile storage permission description

Supported options for acl:

  • READONLY: Readable by all users, writable only by the creator and administrators.
  • PRIVATE: Readable and writable only by the creator and administrators.
  • ADMINWRITE: Readable by all users, writable only by administrators.
  • ADMINONLY: Readable and writable only by administrators

3. Return Results

FieldRequiredTypeDescription
RequestIdRequiredStringRequest ID

4. Sample Code

import CloudBase from "@cloudbase/manager-node";

const { storage } = new CloudBase({
secretId: "Your SecretId",
secretKey: "Your SecretKey",
envId: "Your envId", // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
});

async function test() {
await storage.setStorageAcl("READONLY");
}

test();

listCurrentDirectory

1. API Description

API feature: List files and subdirectories in the specified directory (non-recursive, current level only)

API declaration: app.storage.listCurrentDirectory(dirPath?: string): Promise<Object>

version tip

This API has been supported since v5.0.0.

2. Input Parameters

FieldRequiredTypeDescription
dirPathOptionalStringCloud directory path. If not provided, the root directory is listed; no trailing / required.

3. Return Results

FieldTypeDescription
filesIListFileInfo[]File list at the current level
directoriesString[]List of subdirectory names at the current level

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
const { files, directories } = await app.storage.listCurrentDirectory('images')
console.log('File:', files)
console.log('Subdirectory:', directories)
}

test()

copyFile

1. API Description

API feature: copies a single cloud file to a new path

API declaration: app.storage.copyFile(options: ICopyOptions): Promise<ICopyResult>

version tip

This API has been supported since v5.0.0.

2. Input Parameters

ICopyOptions

FieldRequiredTypeDescription
sourcePathRequiredStringSource file cloud path, for example images/a.jpg
destPathRequiredStringTarget file cloud path, for example backup/a.jpg
forceNoBooleanwhether to forcibly overwrite existing target files, defaults to false
skipExistingNoBooleanSkip if target already exists (without error), default false

3. Return Results

ICopyResult

FieldTypeDescription
successBooleanwhether the operation was successful
sourcePathStringSource path
destPathStringTarget path
sizeNumberFile size (bytes)
statusStringStatus: copied / skipped / failed
errorStringError message when the operation fails

4. Sample Code

async function test() {
const result = await app.storage.copyFile({
sourcePath: 'images/logo.png',
destPath: 'backup/logo.png',
force: true
})
console.log('Copy result:', result)
}

test()

copyDirectory

1. API Description

API feature: recursively copies cloud directories to a new path, supports glob filtering and concurrency control

API declaration: app.storage.copyDirectory(options: ICopyDirectoryOptions): Promise<ICopyResult[]>

version tip

This API has been supported since v5.0.0.

2. Input Parameters

ICopyDirectoryOptions (extends ICopyOptions)

FieldRequiredTypeDescription
sourcePathRequiredStringCloud path of the source directory
destPathRequiredStringCloud path of the target directory
forceNoBooleanwhether to forcibly overwrite existing files, defaults to false
skipExistingNoBooleanSkip if target already exists, default false
includeNoString | String[]Include pattern (glob format)
excludeNoString | String[]Exclude pattern (glob format)
parallelNoNumberConcurrency, default 20
onProgressNoFunctionProgress callback (info: ICopyProgress) => void

ICopyProgress

FieldTypeDescription
copiedNumberCopied count
skippedNumberSkipped count
totalNumberTotal file count
currentFileStringFile being processed

3. Return Results

Promise<ICopyResult[]> — An array of copy results for each file, with the same structure as the return value of copyFile.

4. Sample Code

async function test() {
const results = await app.storage.copyDirectory({
sourcePath: 'src-dir/',
destPath: 'dest-dir/',
include: ['**/*.jpg', '**/*.png'],
force: true,
onProgress: ({ copied, total }) => console.log(`${copied}/${total}`)
})
console.log('Directory copy completed, total:', results.length, 'files')
}

test()

moveFile

1. API Description

API feature: moves a single cloud file to a new path (copies and then deletes the source file)

API declaration: app.storage.moveFile(options: ICopyOptions): Promise<ICopyResult>

version tip

This API has been supported since v5.0.0.

2. Input Parameters

Same as copyFile, with exactly the same parameter structure.

ICopyOptions

FieldRequiredTypeDescription
sourcePathRequiredStringCloud path of the source file
destPathRequiredStringCloud path of the target file
forceNoBooleanwhether to forcibly overwrite existing target files, defaults to false
skipExistingNoBooleanSkip if target already exists, default false

3. Return Results

Same as copyFile, returns ICopyResult.

4. Sample Code

async function test() {
const result = await app.storage.moveFile({
sourcePath: 'temp/upload.jpg',
destPath: 'images/upload.jpg',
force: true
})
console.log('Move result:', result.status)
}

test()

moveDirectory

1. API Description

API feature: recursively move a cloud directory to a new path (copy and then delete the source directory)

API declaration: app.storage.moveDirectory(options: ICopyDirectoryOptions): Promise<ICopyResult[]>

version tip

This API has been supported since v5.0.0.

2. Input Parameters

Same as copyDirectory, with exactly the same parameter structure.

3. Return Results

Same as copyDirectory, returns ICopyResult[].

4. Sample Code

async function test() {
const results = await app.storage.moveDirectory({
sourcePath: 'old-dir/',
destPath: 'new-dir/',
force: true
})
console.log('Directory move completed, total:', results.length, 'files')
}

test()

searchFiles

1. API Description

API feature: Search for files in a specified directory using a glob pattern or regular expression.

API declaration: app.storage.searchFiles(options: ISearchOptions): Promise<ISearchResult[]>

version tip

This API has been supported since v5.0.0.

2. Input Parameters

ISearchOptions

FieldRequiredTypeDescription
patternRequiredStringSearch pattern, supporting glob or regular expression strings
pathOptionalStringSearch directory path. If not specified, the root directory is searched.
isRegexNoBooleanWhen true, parses pattern as a regular expression; default false
fileTypeOptionalStringFile type filtering, e.g., jpg, png
limitOptionalNumberMaximum number of results to return, default 100
includeDetailsNoBooleanwhether to include file size and modification time, default false

3. Return Results

ISearchResult[]

FieldTypeDescription
keyStringCloud file path
typeStringType: file / directory
sizeNumberFile size (bytes), only valid for files
lastModifiedStringLast modified time (in ISO format), only valid for files

4. Sample Code

async function test() {
const results = await app.storage.searchFiles({
pattern: '**/*.jpg',
path: 'images',
limit: 50,
includeDetails: true
})
results.forEach(f => console.log(f.key, f.size))
}

test()