SDK Management Files
CloudBase cloud storage provides comprehensive file management capabilities, including operations such as uploading, downloading, deleting, copying files, and obtaining temporary links. This article will detail how to use these features and related considerations.
Upload files
You can upload any number and format of files to CloudBase Cloud Storage, and customize the paths and names of files and directories.
By default, only users who have passed CloudBase Authentication can upload/delete files to/from cloud storage. Therefore, client-side file uploads require prior login authentication.
You can also use Custom Security Rules to set more relaxed or stricter read/write permissions for cloud storage.
Using the SDK, you can upload files to cloud storage and obtain a globally unique identifier fileID for the file.
- Web SDK
- Mini Program SDK
- Node.js SDK
//Step 1: Introduce the Web SDK.
import tcb from "@cloudbase/js-sdk";
//Step two: perform initialization.
const app = tcb.init({
env: "your-env-id",
});
/**
Step three: login authentication process. The code is omitted here. See:
https://docs.cloudbase.net/authentication-v2/auth/introduce
*/
app
.uploadFile({
// Path of cloud storage.
cloudPath: "dirname/filename",
// File to be uploaded. File type.
filePath: document.getElementById("file").files[0],
})
.then((res) => {
// Return the file ID.
console.log(res.fileID);
});
//First, use wx.cloud.init for initialization. There is no need to import the SDK again on the mini program side, and authentication is not required.
wx.cloud
.uploadFile({
cloudPath: "example.png", // Path of uploading files to the cloud.
filePath: "", // Temporary file path of the mini program, which needs to be obtained using the relevant Mini Program APIs.
})
.then((res) => {
// Return the file ID.
console.log(res.fileID);
});
const tcb = require("@cloudbase/node-sdk");
const fs = require("fs");
const app = tcb.init();
app
.uploadFile({
cloudPath: "path/test.jpg",
fileContent: fs.createReadStream("test.jpg"),
})
.then((res) => {
// Return the file ID.
console.log(res.fileID);
});
- When uploading, the file name must comply with file naming conventions;
- cloudPath is the path relative to the root directory of cloud storage files or folders, in the form of directory/filename, and should not start with
/
; - If a file is uploaded to the same path, it will overwrite the existing file. By default, user A is not allowed to overwrite user B's files.
Download files
By default, files in CloudBase cloud storage are publicly readable to all users.
You can also use Custom Security Rules to set more relaxed or stricter read/write permissions for cloud storage.
Using the SDK, you can download files from the cloud storage space. Pass the globally unique fileID of the cloud storage file when calling.
- Web SDK
- WeChat Mini Program SDK
- Node.js SDK
//Step 1: Introduce the Web SDK.
import tcb from "@cloudbase/js-sdk";
//Step two: perform initialization.
const app = tcb.init({
env: "your-env-id"
});
/**
Step three: login authentication process. The code is omitted here. See:
https://docs.cloudbase.net/authentication-v2/auth/introduce
*/
app
.downloadFile({
fileID: "cloud://a/b/c"
})
.then((res) => {
console.log(res);
});
// You must first initialize using wx.cloud.init. For Mini Programs, there is no need to introduce the SDK, and authentication is exempted.
wx.cloud
.downloadFile({
fileID: "cloud://a/b/c" // File ID
})
.then((res) => {
// Return a temporary file path.
console.log(res.tempFilePath);
});
const tcb = require("@cloudbase/node-sdk");
const app = tcb.init({
env: "your-env-id"
});
app
.downloadFile({
fileID: "cloud://a/b/c"
})
.then((res) => {
// fileContent is of type Buffer.
console.log(res.fileContent);
});
If you need to directly download files from cloud storage in the browser or use cloud storage as an image host, you can use the file's download address or obtain a temporary file link.
Deleting Files
By default, only users who have passed CloudBase authentication can upload/delete files in cloud storage. Therefore, when deleting files on the client side, login authentication must first be performed.
- A single call can delete up to 50 files at most; larger quantities require batch processing.
- By default, only the uploader/creator of the file and administrators have permission to delete the corresponding file. It is not allowed for User A to delete files belonging to User B.
- You can also use custom security rules to set more lenient or stricter read/write permissions for cloud storage.
Using the SDK to call the deleteFile to delete one or multiple specified files in the cloud storage space.
- Web
- WeChat Mini Program
- Node.js
//Step 1: Introduce the Web SDK.
import tcb from "@cloudbase/js-sdk";
//Step two: perform initialization.
const app = tcb.init({
env: "your-env-id",
});
//Step three: authenticate. The following is not complete code; you need to select a login method. For details, refer to "Quick Start" - "Authentication and Examples".
const auth = app.auth({
persistence: "local", // Remains valid for 30 days until the user explicitly logs out or changes the password
});
app
.deleteFile({
fileList: ["cloud://a/b/c", "cloud://d/e/f"],
})
.then((res) => {
console.log(res.fileList);
});
//First, use wx.cloud.init for initialization. There is no need to import the SDK again on the mini program side, and authentication is not required.
wx.cloud
.deleteFile({
fileList: ["cloud://a/b/c", "cloud://d/e/f"],
})
.then((res) => {
console.log(res.fileList);
});
const tcb = require("@cloudbase/node-sdk");
const app = tcb.init();
app
.deleteFile({
fileList: ["cloud://a/b/c", "cloud://d/e/f"],
})
.then((res) => {
console.log(res.fileList);
});
Copy files
You can use the Node.js SDK and Open API to copy files in cloud storage space to a specified path. By setting parameters, you can achieve the effect of moving files. This API supports batch copying. API documentation reference:
- The target file path cannot be the same as the source file path
- Renaming during the copy process is not supported; that is, the file name should remain consistent before and after copying
- The execution of copy operations is affected by bucket permissions, source file and path permissions, and target file and path permissions. Performing a copy operation does not change the original file permissions.
- The number of files in a single operation should not exceed 50; larger quantities require batch processing.
- Node.js
// Initialize the sdk
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: 'xxx' // Fill in the environment ID
})
const path = 'a.png' // Fill in the source file path
const fileList = [{
srcPath: path,
dstPath: `dst/${path}`, // Fill in the target file path
removeOriginal: true // Delete source files after copying, equivalent to moving files
}]
const result = await app.copyFile({
fileList
})
File Naming Restrictions
When using CloudBase cloud storage, file names must comply with the following rules:
- Cannot be empty
- Cannot start with /
- Consecutive / are not allowed
- The encoded length must not exceed 850 bytes
- It is recommended to use uppercase and lowercase English letters, digits, i.e., [a-z, A-Z, 0-9], and the symbols -, !, _, ., *, and their combinations.
- The following ASCII control characters are not supported: up arrow (↑), down arrow (↓), right arrow (→), left arrow (←), corresponding to CAN(24), EM(25), SUB(26), ESC(27) respectively.
- If the name of a file or folder uploaded by a user contains Chinese characters, the Chinese portion will be converted to percent-encoding according to URL encoding rules when accessing or requesting the file or folder.
- Special characters not recommended for use: ` ^ " \ { } [ ] ~ % # \ > < and ASCII 128-255 decimal
- Special characters that may require special handling before use: , : ; = & \$ @ + ? (space), and ASCII characters in the range: 00-1F hex (0-31 decimal) and 7F (127 decimal)
Get a temporary link
You can use fileID to retrieve the https link for the specified file in cloud storage space (cloud storage provides a free CDN domain).
- The https link obtained for files with public read permission does not expire; for example, the default permission is public read, and the obtained link is permanently valid.
- For files with private read permission, the obtained https links are temporary. For example, you can combine user authentication and security rules to set file permissions so that only the file's uploader or administrator can read it. In this case, only users who have passed cloud development authentication have permission to obtain temporary links.
- The validity period can be set dynamically. Requests for temporary links beyond the validity period will be rejected, ensuring file security.
- Up to 50 can be retrieved at a time; additional ones require batch processing.
Set public read steps
Go to Cloud Development Platform - Object Storage - Permission Settings
By using the SDK to call the getTempFileURL method and pass in the file's fileID, you can retrieve the https link for the specified file in cloud storage.
- Web SDK
- WeChat Mini Program SDK
- Node.js SDK
//Step 1: Introduce the Web SDK.
import tcb from "@cloudbase/js-sdk";
//Step two: perform initialization.
const app = tcb.init({
env: "your-env-id",
});
//Step three: authenticate. The following is not complete code; you need to select a login method. For details, refer to "Quick Start" - "Authentication and Examples".
const auth = app.auth({
persistence: "local", // Remains valid for 30 days until the user explicitly logs out or changes the password
});
app
.getTempFileURL({
fileList: ["cloud://a/b/c", "cloud://d/e/f"],
})
.then((res) => {
// fileList is an object array with the following structure.
// [{
// fileID: 'cloud://webtestjimmy-5328c3.7765-webtestjimmy-5328c3-1251059088/Tencent Cloud.png', // File ID.
// tempFileURL: '', // Temporary file network connection.
// maxAge: 120 * 60 * 1000, // Validity period.
// }]
console.log(res.fileList);
});
//First, use wx.cloud.init for initialization. There is no need to import the SDK again on the mini program side, and authentication is not required.
wx.cloud
.getTempFileURL({
fileList: ["cloud://a/b/c", "cloud://d/e/f"],
})
.then((res) => {
// fileList is an object array with the following structure.
// [{
// fileID: 'cloud://webtestjimmy-5328c3.7765-webtestjimmy-5328c3-1251059088/Tencent Cloud.png', // File ID.
// tempFileURL: '', // Temporary file network connection.
// maxAge: 120 * 60 * 1000, // Validity period.
// }]
console.log(res.fileList);
});
const tcb = require("@cloudbase/node-sdk");
const app = tcb.init();
app
.getTempFileURL({
fileList: ["cloud://a/b/c", "cloud://d/e/f"],
})
.then((res) => {
// fileList is an object array with the following structure.
// [{
// fileID: 'cloud://webtestjimmy-5328c3.7765-webtestjimmy-5328c3-1251059088/Tencent Cloud.png', // File ID.
// tempFileURL: '', // Temporary file network connection.
// maxAge: 120 * 60 * 1000, // Validity period.
// }]
console.log(res.fileList);
});