Initialization
Quick Start
- Initialize a BosClient using STS authentication.
The BosClient acts as a client for interfacing with BOS services, and all BOS operations in the BOS Harmony SDK are performed via the BosClient. Example code:
1let credential = new Credential(<AccessKeyID>, <SecretAccessKey>, <Token>); ; //Temporary AK/SK and Token returned by STS
2let clientOptions = new ClientOptions();
3 clientOptions.endpoint = "bj.bcebos.com"; //Pass in the domain name of the region where the bucket is located
4 let bosClient = new BosClient(credential, clientOptions); // Create BosClient
Note: Harmony SDK is primarily used for mobile development scenarios. Mobile an untrusted environment, and there is a high risk of directly saving AccessKeyId and SecretAccessKey in the terminal for signing requests. Therefore, it is recommended to use the STS authentication mode. For detailed introduction to STS, please refer to Temporary Authorization Access.
- Create a bucket.
A bucket is a namespace in BOS that acts as a container for data, capable of storing multiple data entities (objects). Before uploading data, you need to create a bucket. Example code:
1let location: string;
2let bucketName = "test-bucket-harmony";
3try {
4 location = await bosClient.putBucket(<bucketName>);
5 logger.info(`create bucket success, location:${location}`);
6 } catch (bosResponse) { // Failed to create bucket
7 printErrorInfo(bosResponse, "put bucket error"); // Print error information
8}
- Upload an object.
An object is the basic data unit in BOS. You can think of an object as a file. For uploading simple objects, BOS provides a method to upload binary strings. Example code:
1let cacheDir = getContext().cacheDir;
2let path = cacheDir + '/test.txt';
3let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE | fs.OpenMode.TRUNC)
4fs.writeSync(file.fd, "Hello BOS");
5fs.fsyncSync(file.fd);
6fs.closeSync(file.fd);
7 file = fs.openSync(path, fs.OpenMode.READ_ONLY); // Open the file synchronously
8 let stat = fs.lstatSync(path); //Get file information
9 let buf = new ArrayBuffer(stat.size); //Construct ArrayBuffer
10 fs.readSync(file.fd, buf); // Read file content
11fs.fsyncSync(file.fd);
12fs.closeSync(file.fd);
13let etag: string;
14try {
15 etag = await bosClient.putObject(<bucketName>, <objectName>, buf); //Upload object
16 logger.info(put object success, etag:${etag}); // Print etag
17} catch (bosResponse) {
18 printErrorInfo(bosResponse, "put object fail");
19}
- View the list of objects within a bucket.
After completing a series of uploads, you can use the following code to list all objects within a bucket. Example code:
1let listObjectsResult: ListObjectsResult;
2try {
3 listObjectsResult = await bosClient.listObjects(<bucketName>);
4 // Traverse all objects
5for (let objectInfo of listObjectsResult.contents as ObjectSummaryType[]) {
6 logger.info(`name: ${objectInfo.key} size: ${objectInfo.size} storageClass: ${objectInfo.storageClass}`);
7}
-
Get the speciied object.
Use the following example code to retrieve one or more objects. Example code:
1let getObjectResult: GetObjectResult;
2 try { // Note: The current API only supports downloading objects no larger than 5 MB
3 getObjectResult = await bosClient.getObject(, );
4 logger.info(`get object success, etag:${JSON.stringify(getObjectResult.etag)}`);
5} catch (bosResponse) {
6 printErrorInfo(bosResponse, "get object fail");
7}
Complete example
1import fs from '@ohos.file.fs';
2import { logger, Credential, BosClient, ClientOptions} from "bos"
3import { BosResponse } from "bos/src/main/ets/bos/model/BosResponse"
4 // All classes of return results below are in this path
5import { GetObjectResult, ObjectSummaryType, ListObjectsResult, ListObjectsArgs } from "bos/src/main/ets/bos/api/DataType
6function printErrorInfo(bosResponse: BosResponse, prefix: string) {
7 logger.error(`${prefix}, info: ${JSON.stringify(bosResponse.error)}`);
8}
9export async function fastStart() {
10 let AccessKeyID = ""
11 let SecretAccessKey = ""
12 let Token = ""
13 let objectName = "test-object"
14 let credential = new Credential(AccessKeyID, SecretAccessKey, Token); //Temporary AK/SK and Token returned by STS
15 let clientOptions = new ClientOptions();
16 clientOptions.endpoint = "bj.bcebos.com"; //Pass in the domain name of the region where the bucket is located
17 let bosClient = new BosClient(credential, clientOptions); // Create BosClient
18 let bucketName = "test-bucket-harmony";
19 let location: string;
20 try {
21 location = await bosClient.putBucket(bucketName);
22 logger.info(`create bucket success, location:${location}`);
23 } catch (bosResponse) { // Failed to create bucket
24 printErrorInfo(bosResponse, "put bucket error"); // Print error information
25 }
26 // Create a temporary file
27 let cacheDir = getContext().cacheDir;
28 let path = cacheDir + '/test.txt';
29 let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE | fs.OpenMode.TRUNC)
30 fs.writeSync(file.fd, "Hello BOS");
31 fs.fsyncSync(file.fd);
32 fs.closeSync(file.fd);
33 file = fs.openSync(path, fs.OpenMode.READ_ONLY); // Open the file synchronously
34 let stat = fs.lstatSync(path); //Get file information
35 let buf = new ArrayBuffer(stat.size); //Construct ArrayBuffer
36 fs.readSync(file.fd, buf); // Read file content
37 fs.fsyncSync(file.fd);
38 fs.closeSync(file.fd);
39 let etag: string;
40 try {
41 etag = await bosClient.putObject(bucketName, objectName, buf); //Upload object
42 logger.info(put object success, etag:${etag}); // Print etag
43 } catch (bosResponse) {
44 printErrorInfo(bosResponse, "put object fail");
45 }
46 let args = new ListObjectsArgs();
47 let listObjectsResult: ListObjectsResult;
48
49 try {
50 listObjectsResult = await bosClient.listObjects(bucketName, args);
51 // Traverse all objects
52 for (let objectInfo of listObjectsResult.contents as ObjectSummaryType[]) {
53 logger.info(`name: ${objectInfo.key} size: ${objectInfo.size} storageClass: ${objectInfo.storageClass}`);
54 }
55 } catch (bosResponse) {
56 printErrorInfo(bosResponse, "list objects error");
57 }
58 let getObjectResult: GetObjectResult;
59 try {
60 getObjectResult = await bosClient.getObject(bucketName, objectName);
61 logger.info(`get object success, etag:${JSON.stringify(getObjectResult.etag)}`);
62 } catch (bosResponse) {
63 printErrorInfo(bosResponse, "get object fail");
64 }
65}
Configure BosClient
To configure specific parameters for the BosClient, users can provide a ClientOptions object during its initialization. The ClientOptions class allows the configuration of basic network parameters for the BOS Service.
-
Example code
let clientOptions = new ClientOptions(); //Create ClientOptions object clientOptions.calcMd5On = true; //Calculate MD5 locally when uploading objects clientOptions.endpoint = "bj.bcebos.com"; // Set domain name clientOptions.multiPartSize = 6164480; //Size of each part during multipart upload
- Parameter description
| Parameters | Description |
|---|---|
| endpoint | Domain name addresses of BOS services in various regions |
| userAgent | User agent, refers to HTTP’s User-Agent header |
| signExpireSeconds | Signature validity period, in seconds |
| connectTimeout | Timeout duration for establishing connections (unit: ms), with a default value of 10000 |
| multiPartSize | Part size, defaulting to 5242880 |
| calcMd5On | Choose whether to calculate the MD5 value locally when uploading an object. The default setting is false. Note: Enabling this option by setting it to true will increase upload time. |
Configure HTTPS access to BOS
Set the endpoint as
-
Example code
let clientOptions = new ClientOptions(); //Create ClientOptions object clientOptions.endpoint = "https://bj.bcebos.com"; // Set domain name
