### Multipart Upload to OBS using BrowserJS SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/simple-multipart-upload-sample.html This function demonstrates the process of uploading a file in multiple parts to Huawei Cloud Object Storage Service (OBS) using the OBS BrowserJS SDK. It requires basic OBS configuration including AK, SK, server endpoint, and bucket name. The function first initiates the multipart upload, then uploads individual parts, and finally completes the upload. Errors during any step will be logged. ```javascript function getObsClient(){ var ak = document.getElementById('ak').value; var sk = document.getElementById('sk').value; var server = document.getElementById('server').value; return new ObsClient({ access_key_id: ak, secret_access_key: sk, server : server, timeout : 60 * 5, }); } function doMultipartUpload(){ var bucketName = document.getElementById('bucketname').value; var objectKey = document.getElementById('objectkey').value; var obs = getObsClient(); console.log('Step 1: initiate multipart upload \n'); obs.initiateMultipartUpload({ Bucket: bucketName, Key: objectKey, }).then(function(result) { if(result.CommonMsg.Status < 300){ var uploadId = result.InterfaceResult.UploadId; console.log('Step 2: upload part \n'); obs.uploadPart({ Bucket: bucketName, Key: objectKey, UploadId: uploadId, PartNumber : 1, Body : 'Hello OBS' }).then(function(result) { if(result.CommonMsg.Status < 300){ var etag = result.InterfaceResult.ETag; console.log('Step 3: complete multipart upload \n'); obs.completeMultipartUpload({ Bucket : bucketName, Key : objectKey, UploadId: uploadId, Parts : [{"PartNumber" : 1, "ETag": etag}] }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('complete multipart upload finished.\n'); } }); } }); } }); } ``` -------------------------------- ### Object Operations API Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/object-operations-sample.html This section covers various object operations including putting, getting, copying, and deleting objects, as well as managing their ACLs using the OBS SDK for BrowserJS. ```APIDOC ## Object Operations API ### Description This API group provides functionalities to perform common object operations on OBS using the BrowserJS SDK. It includes creating (putting), retrieving (getting), copying, and deleting objects, along with managing their access control lists (ACLs). ### Operations #### Put Object * **Method**: POST (Implicitly via SDK) * **Endpoint**: N/A (SDK method) * **Description**: Uploads an object to a specified bucket. * **Request Body Example**: ```json { "Bucket": "your-bucket-name", "Key": "your-object-key", "Body": "Hello OBS" } ``` * **Success Response Example**: ```json { "CommonMsg": { "Status": 200, "StatusText": "OK" } } ``` #### Get Object Metadata * **Method**: GET (Implicitly via SDK) * **Endpoint**: N/A (SDK method) * **Description**: Retrieves the metadata of a specified object. * **Request Body Example**: ```json { "Bucket": "your-bucket-name", "Key": "your-object-key" } ``` * **Success Response Example**: ```json { "CommonMsg": { "Status": 200, "StatusText": "OK" }, "InterfaceResult": { "ETag": "", "ContentLength": 12345 } } ``` #### Get Object * **Method**: GET (Implicitly via SDK) * **Endpoint**: N/A (SDK method) * **Description**: Downloads the content of a specified object. * **Request Body Example**: ```json { "Bucket": "your-bucket-name", "Key": "your-object-key" } ``` * **Success Response Example**: ```json { "CommonMsg": { "Status": 200, "StatusText": "OK" }, "InterfaceResult": { "Content": "" } } ``` #### Copy Object * **Method**: PUT (Implicitly via SDK) * **Endpoint**: N/A (SDK method) * **Description**: Copies an object from a source to a destination within OBS. * **Request Body Example**: ```json { "Bucket": "destination-bucket-name", "Key": "destination-object-key", "CopySource": "source-bucket-name/source-object-key", "MetadataDirective": "COPY" } ``` * **Success Response Example**: ```json { "CommonMsg": { "Status": 200, "StatusText": "OK" }, "InterfaceResult": { "ETag": "" } } ``` #### Set Object ACL * **Method**: PUT (Implicitly via SDK) * **Endpoint**: N/A (SDK method) * **Description**: Sets the Access Control List (ACL) for a specified object. * **Request Body Example**: ```json { "Bucket": "your-bucket-name", "Key": "your-object-key", "ACL": "public-read" } ``` * **Success Response Example**: ```json { "CommonMsg": { "Status": 200, "StatusText": "OK" } } ``` #### Get Object ACL * **Method**: GET (Implicitly via SDK) * **Endpoint**: N/A (SDK method) * **Description**: Retrieves the Access Control List (ACL) for a specified object. * **Request Body Example**: ```json { "Bucket": "your-bucket-name", "Key": "your-object-key" } ``` * **Success Response Example**: ```json { "CommonMsg": { "Status": 200, "StatusText": "OK" }, "InterfaceResult": { "Owner": { "ID": "", "Name": "" }, "Grants": [ { "Grantee": { "ID": "", "Name": "", "URI": "" }, "Permission": "READ" } ] } } ``` #### Delete Object * **Method**: DELETE (Implicitly via SDK) * **Endpoint**: N/A (SDK method) * **Description**: Deletes a specified object from a bucket. * **Request Body Example**: ```json { "Bucket": "your-bucket-name", "Key": "your-object-key" } ``` * **Success Response Example**: ```json { "CommonMsg": { "Status": 200, "StatusText": "OK" } } ``` ``` -------------------------------- ### Set and Get Bucket Quota using OBS SDK for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/bucket-operations-sample.html Demonstrates setting and then retrieving the storage quota for an OBS bucket. The `setBucketQuota` function requires the bucket name and the desired quota size in bytes. The `getBucketQuota` function retrieves the current quota. ```javascript function doBucketQuota(){ var bucketName = document.getElementById('bucketname').value; var obs = getObsClient(); obs.setBucketQuota({ Bucket : bucketName, StorageQuota : 1024 * 1024 * 1024 * 1024 }).then(function(result) { obs.getBucketQuota({ Bucket : bucketName }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Get bucket quota ' + result.InterfaceResult.StorageQuota + '\n'); } } ); }); } ``` -------------------------------- ### Manage Bucket Logging using OBS SDK for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/bucket-operations-sample.html Configures, retrieves, and deletes the logging configuration for an OBS bucket. This involves setting a target bucket and prefix for logs, then getting the current settings, and finally disabling logging. Requires bucket name and OBS client. ```javascript function doBucketLogging(){ var bucketName = document.getElementById('bucketname').value; var obs = getObsClient(); obs.setBucketLogging({ Bucket: bucketName, Agency: 'test', LoggingEnabled:{ TargetBucket:bucketName, TargetPrefix:'log-' } }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Set bucket logging finished.\n'); obs.getBucketLogging({ Bucket : bucketName }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Get bucket logging:'); console.log('\tTargetBucket-->' + result.InterfaceResult.LoggingEnabled.TargetBucket); console.log('\tTargetPrefix-->' + result.InterfaceResult.LoggingEnabled.TargetPrefix); console.log('\n'); obs.setBucketLogging({ Bucket : bucketName }).then(function(result){ if(result.CommonMsg.Status < 300){ console.log('Delete bucket logging finished.\n'); } }); } }); }else{ console.log('Status-->' + result.CommonMsg.Status); console.log('Code-->' + result.CommonMsg.Code); console.log('Message-->' + result.CommonMsg.Message); } }); } ``` -------------------------------- ### Create Temporary Signed URLs with JavaScript Source: https://context7.com/huaweicloud/huaweicloud-sdk-browserjs-obs/llms.txt Generates time-limited URLs for secure, temporary access to OBS objects. These URLs can be used for GET (download) or PUT (upload) requests without requiring permanent credentials. The function takes HTTP method, bucket name, object key, and expiration time as input, returning the signed URL. ```javascript const bucketName = 'my-bucket'; const objectKey = 'documents/private-report.pdf'; // Create signed URL for GET request (download) const getSignedUrl = obsClient.createSignedUrlSync({ Method: 'GET', Bucket: bucketName, Key: objectKey, Expires: 3600 // URL valid for 1 hour (3600 seconds) }); console.log('Signed URL for download:'); console.log(getSignedUrl.SignedUrl); console.log('Expires in: 1 hour\n'); // Create signed URL for PUT request (upload) const putSignedUrl = obsClient.createSignedUrlSync({ Method: 'PUT', Bucket: bucketName, Key: 'uploads/new-file.txt', Expires: 1800, // URL valid for 30 minutes Headers: { 'Content-Type': 'text/plain' } }); console.log('Signed URL for upload:'); console.log(putSignedUrl.SignedUrl); console.log('Expires in: 30 minutes\n'); // Using the signed URL with fetch API fetch(getSignedUrl.SignedUrl) .then(response => response.text()) .then(content => { console.log('Downloaded content via signed URL:'); console.log(content); }) .catch(error => { console.error('Error using signed URL:', error); }); ``` -------------------------------- ### Get OBS Object with Temporary Signature (BrowserJS) Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/temporary-signature-sample.html Retrieves an object from an OBS bucket using a temporary signature. It generates a signed URL for the GET operation and then uses the doAction function to fetch the object. Requires bucket name and object key. The content parameter for doAction is null as it's a GET request. ```javascript function getObject(){ var bucketName = document.getElementById('bucketname').value; var objectKey = document.getElementById('objectkey').value; var obs = getObsClient(); var method = 'GET'; var res = obs.createV2SignedUrlSync({Method : method, Bucket : bucketName, Key: objectKey}); doAction('Get object', method, res.SignedUrl, null, res.ActualSignedRequestHeaders); } ``` -------------------------------- ### Initialize OBS Client and Create Folder using BrowserJS SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/create-folder-sample.html This snippet demonstrates how to initialize an OBS client instance using provided Access Key ID, Secret Access Key, and server endpoint. It then shows two ways to create an empty folder within a specified bucket using the `putObject` method. The first way creates the folder by simply providing a key ending with a slash, while the second way explicitly sets the Body to an empty string. It also includes logic to verify the folder creation and check its size. ```javascript function getObsClient(){ var ak = document.getElementById('ak').value; var sk = document.getElementById('sk').value; var server = document.getElementById('server').value; return new ObsClient({ access_key_id: ak, secret_access_key: sk, server : server, timeout : 60 * 5, }); } function createFolder(){ var bucketName = document.getElementById('bucketname').value; var obs = getObsClient(); /* * Way 1: */ var keySuffixWithSlash1 = 'MyObjectKey1/'; obs.putObject({ Bucket : bucketName, Key : keySuffixWithSlash1 }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Create an empty folder ' + keySuffixWithSlash1 + ' finished.\n'); /* * Verify whether the size of the empty folder is zero */ obs.getObjectMetadata({ Bucket : bucketName, Key : keySuffixWithSlash1 }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Size of the empty folder ' + keySuffixWithSlash1 + ' is ' + result.InterfaceResult.ContentLength); } }); } }); /* * Way 2: */ var keySuffixWithSlash2 = 'MyObjectKey2/'; obs.putObject({ Bucket : bucketName, Key : keySuffixWithSlash2, Body : '' }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Create an empty folder ' + keySuffixWithSlash2 + ' finished.\n'); /* * Verify whether the size of the empty folder is zero */ obs.getObjectMetadata({ Bucket : bucketName, Key : keySuffixWithSlash1 }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Size of the empty folder ' + keySuffixWithSlash2 + ' is ' + result.InterfaceResult.ContentLength); } }); } }); } ``` -------------------------------- ### Get OBS Object ACL with Temporary Signature (BrowserJS) Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/temporary-signature-sample.html Retrieves the Access Control List (ACL) of an object in an OBS bucket using a temporary signature. It generates a signed URL for a GET operation with the 'acl' special parameter. Requires bucket name and object key. Content parameter is null. ```javascript function getObjectAcl(){ var bucketName = document.getElementById('bucketname').value; var objectKey = document.getElementById('objectkey').value; var obs = getObsClient(); var method = 'GET'; var res = obs.createV2SignedUrlSync({Method : method, Bucket : bucketName, Key: objectKey, SpecialParam: 'acl'}); doAction('Get object acl', method, res.SignedUrl, null, res.ActualSignedRequestHeaders); } ``` -------------------------------- ### Create Folder API Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/create-folder-sample.html Demonstrates how to create an empty folder in an OBS bucket using the `putObject` method of the OBS SDK for BrowserJS. Two approaches are shown: one implicitly creating the folder by providing a key ending with '/', and another explicitly by providing an empty body. ```APIDOC ## POST // (Implicit Folder Creation) ### Description Creates an empty folder in the specified bucket by providing an object key that ends with a forward slash ('/'). The SDK handles the creation of the folder structure. ### Method POST ### Endpoint `//` ### Parameters #### Path Parameters - **bucketName** (string) - Required - The name of the bucket where the folder will be created. - **objectKeyWithSlash** (string) - Required - The name of the folder to create, ending with '/'. #### Request Body None ### Request Example ```json { "Bucket": "your-bucket-name", "Key": "my-new-folder/" } ``` ### Response #### Success Response (200) - **CommonMsg.Status** (integer) - Indicates the success status of the operation. A status code less than 300 signifies success. #### Response Example ```json { "CommonMsg": { "Status": 200, "Message": "OK" }, "InterfaceResult": {} } ``` --- ## POST // (Explicit Folder Creation) ### Description Creates an empty folder in the specified bucket by providing an object key and an empty request body. This method explicitly defines the folder to be created. ### Method POST ### Endpoint `//` ### Parameters #### Path Parameters - **bucketName** (string) - Required - The name of the bucket where the folder will be created. - **objectKey** (string) - Required - The name of the folder to create. #### Request Body - **Body** (string) - Optional - An empty string indicating no content for the folder. ### Request Example ```json { "Bucket": "your-bucket-name", "Key": "another-folder", "Body": "" } ``` ### Response #### Success Response (200) - **CommonMsg.Status** (integer) - Indicates the success status of the operation. A status code less than 300 signifies success. #### Response Example ```json { "CommonMsg": { "Status": 200, "Message": "OK" }, "InterfaceResult": {} } ``` ``` -------------------------------- ### OBS Client Initialization Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/list-objects-sample.html Initializes an OBS client instance using provided Access Key ID, Secret Access Key, and server endpoint. ```APIDOC ## OBS Client Initialization ### Description Initializes an OBS client instance with your account credentials and server details. ### Method `new ObsClient(config)` ### Parameters #### Request Body - **access_key_id** (string) - Required - Your Access Key ID. - **secret_access_key** (string) - Required - Your Secret Access Key. - **server** (string) - Required - The OBS server endpoint. - **timeout** (number) - Optional - The client timeout in seconds. Defaults to 300 seconds (5 minutes). ### Request Example ```javascript var ak = document.getElementById('ak').value; var sk = document.getElementById('sk').value; var server = document.getElementById('server').value; var obsClient = new ObsClient({ access_key_id: ak, secret_access_key: sk, server: server, timeout: 60 * 5 // 5 minutes timeout }); ``` ### Response #### Success Response (200) An instance of the `ObsClient` is returned. #### Response Example ```javascript // obsClient instance ``` ``` -------------------------------- ### Get Bucket Storage Info Source: https://context7.com/huaweicloud/huaweicloud-sdk-browserjs-obs/llms.txt Retrieves detailed storage statistics for a specified bucket, including total size and object count. This is essential for monitoring storage consumption and associated costs. ```APIDOC ## Get Bucket Storage Info ### Description Retrieves bucket storage statistics. Returns information about the bucket's storage usage including total size and object count. Useful for monitoring storage consumption and billing. ### Method GET (Implicit, as this is a SDK call to retrieve info) ### Endpoint Not directly exposed via HTTP, SDK abstracts this. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const bucketName = 'my-bucket'; obsClient.getBucketStorageInfo({ Bucket: bucketName }).then(function(result) { // ... handle result }).catch(function(error) { // ... handle error }); ``` ### Response #### Success Response (200) - **InterfaceResult** (object) - Contains storage details. - **Size** (number) - Total size of the bucket in bytes. - **ObjectNumber** (number) - Total number of objects in the bucket. - **CommonMsg** (object) - Common message object. - **Status** (number) - HTTP status code. - **Message** (string) - Status message. #### Response Example ```json { "InterfaceResult": { "Size": 15728640000, "ObjectNumber": 1337 }, "CommonMsg": { "Status": 200, "Message": "Success" } } ``` ``` -------------------------------- ### Configure and Initialize OBS Client (BrowserJS) Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/delete-objects-sample.html This function initializes an OBS client instance using provided AK, SK, and server endpoint. It's a prerequisite for interacting with OBS services. The client configuration includes access credentials and the server URL. ```javascript function getObsClient(){ /* * Initialize a obs client instance with your account for accessing OBS */ var ak = document.getElementById('ak').value; var sk = document.getElementById('sk').value; var server = document.getElementById('server').value; return new ObsClient({ access_key_id: ak, secret_access_key: sk, server : server, timeout : 60 * 5 }); } ``` -------------------------------- ### Initialize OBS Client with BrowserJS SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/post-object-sample.html This function initializes an instance of the OBS client for BrowserJS. It requires AK, SK, and server details obtained from input fields. The client is configured with these credentials, the OBS endpoint, and a default signature type and timeout. ```javascript function getObsClient(){ /* * Initialize a obs client instance with your account for accessing OBS */ var ak = document.getElementById('ak').value; var sk = document.getElementById('sk').value; var server = document.getElementById('server').value; return new ObsClient({ access_key_id: ak, secret_access_key: sk, server : server, signature : 'obs', timeout : 60 * 5 }); } ``` -------------------------------- ### Set and Get Bucket Quota Source: https://context7.com/huaweicloud/huaweicloud-sdk-browserjs-obs/llms.txt Allows setting a maximum storage limit (quota) for a bucket and retrieving the current quota configuration. This helps in controlling storage costs and managing storage growth. ```APIDOC ## Set and Get Bucket Quota ### Description Configure storage quota limits for a bucket. Sets a maximum storage limit for a bucket to control costs and prevent unlimited storage growth. The quota is specified in bytes. ### Method POST (for setting), GET (for retrieving) ### Endpoint Not directly exposed via HTTP, SDK abstracts this. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (for `setBucketQuota`) - **Bucket** (string) - Required - The name of the bucket. - **StorageQuota** (number) - Required - The storage quota in bytes. ### Request Example (Set Quota) ```javascript const bucketName = 'my-bucket'; const quotaInGB = 1024; const quotaInBytes = quotaInGB * 1024 * 1024 * 1024; obsClient.setBucketQuota({ Bucket: bucketName, StorageQuota: quotaInBytes }).then(function(result) { // ... handle result }).catch(function(error) { // ... handle error }); ``` ### Request Example (Get Quota) ```javascript obsClient.getBucketQuota({ Bucket: 'my-bucket' }).then(function(result) { // ... handle result }).catch(function(error) { // ... handle error }); ``` ### Response #### Success Response (200) for `getBucketQuota` - **InterfaceResult** (object) - Contains quota details. - **StorageQuota** (number) - The storage quota in bytes. - **CommonMsg** (object) - Common message object. - **Status** (number) - HTTP status code. - **Message** (string) - Status message. #### Response Example (Get Quota) ```json { "InterfaceResult": { "StorageQuota": 1099511627776 }, "CommonMsg": { "Status": 200, "Message": "Success" } } ``` ``` -------------------------------- ### Initialize OBS Client for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/list-objects-sample.html This function initializes an OBS client instance using credentials and server information obtained from HTML input fields. It configures the client with access key ID, secret access key, server URL, and a timeout. Ensure that the input fields with IDs 'ak', 'sk', and 'server' are present in your HTML. ```javascript function getObsClient(){ var ak = document.getElementById('ak').value; var sk = document.getElementById('sk').value; var server = document.getElementById('server').value; return new ObsClient({ access_key_id: ak, secret_access_key: sk, server : server, timeout : 60 * 5, }); } ``` -------------------------------- ### Get Object Metadata using BrowserJS SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/object-operations-sample.html Retrieves the metadata of an object from an OBS bucket. This function requires the bucket name and object key from HTML input fields and utilizes the `getObjectMetadata` method. ```javascript /* * Get object metadata */ function getObjectMetadata(){ var bucketName = document.getElementById('bucketname').value; var objectKey = document.getElementById('objectkey').value; var obs = getObsClient(); obs.getObjectMetadata({ Bucket: bucketName, Key : objectKey }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Get object metadata'); console.log('\tETag-->' + result.InterfaceResult.ETag); console.log('\tContentLength-->' + result.InterfaceResult.ContentLength); console.log('\n'); } }); } ``` -------------------------------- ### Initialize OBS Client (BrowserJS) Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/upload-download-sample.html Initializes an OBS client instance for accessing OBS. Requires user-provided AK, SK, and server endpoint. The client is configured with a timeout value. ```javascript function getObsClient(){ /* * Initialize a obs client instance with your account for accessing OBS */ var ak = document.getElementById('ak').value; var sk = document.getElementById('sk').value; var server = document.getElementById('server').value; return new ObsClient({ access_key_id: ak, secret_access_key: sk, server : server, timeout : 60 * 5, }); } ``` -------------------------------- ### Get Bucket Metadata using OBS SDK for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/bucket-operations-sample.html Retrieves metadata information for a specified OBS bucket. This includes various headers and properties associated with the bucket. The operation requires the bucket name and an initialized OBS client. ```javascript function getBucketMetadata(){ var bucketName = document.getElementById('bucketname').value; var obs = getObsClient(); obs.getBucketMetadata({ Bucket : bucketName }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Get bucket metadata' ``` -------------------------------- ### Get Bucket Location using OBS SDK for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/bucket-operations-sample.html Retrieves the geographical location of a specified OBS bucket. This operation requires the bucket name and a pre-initialized OBS client. The result includes the bucket's location information. ```javascript function getBucketLocation(){ var bucketName = document.getElementById('bucketname').value; var obs = getObsClient(); obs.getBucketLocation({ Bucket : bucketName }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Get bucket location ' + result.InterfaceResult.Location + '\n'); } }); } ``` -------------------------------- ### Client Initialization Source: https://context7.com/huaweicloud/huaweicloud-sdk-browserjs-obs/llms.txt Initializes the ObsClient with credentials and configuration. The client instance is used for all subsequent operations. ```APIDOC ## Client Initialization ### Description Initialize the ObsClient with credentials and configuration. ### Method Constructor ### Endpoint N/A ### Parameters #### Request Body - **access_key_id** (string) - Required - Your OBS access key ID. - **secret_access_key** (string) - Required - Your OBS secret access key. - **server** (string) - Required - The OBS service endpoint URL. - **timeout** (number) - Optional - Request timeout in milliseconds (default is 300000). - **signature** (string) - Optional - Signature version ('v4' or 'obs' for v2, default is 'v4'). - **security_token** (string) - Optional - Security token for temporary credentials (default is null). - **is_secure** (boolean) - Optional - Use HTTPS (default is true). - **port** (number) - Optional - The port for the service endpoint (default is 443). - **path_style** (boolean) - Optional - Use virtual-hosted-style URLs (default is false). - **region** (string) - Optional - The region of the OBS service. - **is_cname** (boolean) - Optional - Enable custom domain support (default is false). ### Request Example ```javascript // Basic client initialization const obsClient = new ObsClient({ access_key_id: 'YOUR_ACCESS_KEY_ID', secret_access_key: 'YOUR_SECRET_ACCESS_KEY', server: 'https://obs.your-region.example.com' }); // Advanced configuration with all options const obsClient = new ObsClient({ access_key_id: 'YOUR_ACCESS_KEY_ID', secret_access_key: 'YOUR_SECRET_ACCESS_KEY', server: 'https://obs.your-region.example.com', timeout: 300000, signature: 'v4', security_token: null, is_secure: true, port: 443, path_style: false, region: 'your-region', is_cname: false }); ``` ### Response #### Success Response (200) N/A (Constructor does not return a value, initializes the client object.) #### Response Example N/A ``` -------------------------------- ### List Objects Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/list-objects-sample.html Demonstrates how to list objects within a specified bucket using the OBS SDK for BrowserJS. Supports default listing (up to 1000 objects), pagination, and grouping by folder. ```APIDOC ## List Objects ### Description Lists objects within a specified OBS bucket. This operation supports various listing modes including default listing, paginated listing, and listing objects grouped by folder. ### Method `obs.listObjects(options)` ### Parameters #### Path Parameters - **Bucket** (string) - Required - The name of the bucket. #### Query Parameters - **MaxKeys** (number) - Optional - The maximum number of objects to return in a single request. Defaults to 1000. - **Marker** (string) - Optional - Specifies the starting point for the list. Objects after this marker will be returned. - **Delimiter** (string) - Optional - A delimiter used to group objects. For example, using `/` groups objects into common prefixes (folders). - **Prefix** (string) - Optional - Returns only objects that start with the specified prefix. ### Request Example #### Default List Objects ```javascript obs.listObjects({ Bucket: bucketName }).then(function(result) { // Process result }); ``` #### Paginated List Objects ```javascript function listAll(nextMarker, pageSize, pageIndex) { obs.listObjects({ Bucket: bucketName, MaxKeys: pageSize, Marker: nextMarker }).then(function(result) { if (result.CommonMsg.Status < 300) { console.log('Page:' + pageIndex + '\n'); // Process contents if (result.InterfaceResult.IsTruncated === 'true') { listAll(result.InterfaceResult.NextMarker, pageSize, pageIndex + 1); } } }); } listAll(null, 20, 1); ``` #### List Objects by Folder ```javascript obs.listObjects({ Bucket: bucketName, Delimiter: '/' }).then(function(result) { // Process root path contents and common prefixes (folders) }); ``` ### Response #### Success Response (200) - **CommonMsg** (object) - Contains common message information, including status. - **InterfaceResult** (object) - Contains the result of the operation. - **Contents** (array) - An array of objects, where each object has: - **Key** (string) - The object key. - **ETag** (string) - The ETag of the object. - **IsTruncated** (string) - Indicates if the list is truncated ('true' or 'false'). - **NextMarker** (string) - The marker for the next page of results, if `IsTruncated` is 'true'. - **CommonPrefixes** (array) - An array of common prefixes (folders) if `Delimiter` is used. #### Response Example ```json { "CommonMsg": { "Status": 200, "Message": "", "Code": "", "HttpStatusCode": 200 }, "InterfaceResult": { "Contents": [ { "Key": "MyObjectKey0", "LastModified": "2023-10-27T10:00:00.000Z", "ETag": "etag1", "Size": 100, "StorageClass": "STANDARD" } ], "IsTruncated": "false", "NextMarker": null, "CommonPrefixes": [ { "Prefix": "MyFolder/" } ] } } ``` ``` -------------------------------- ### Get Bucket Storage Info using OBS SDK for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/bucket-operations-sample.html Fetches the storage information for a specified OBS bucket, including its size and the number of objects it contains. This function requires the bucket name and an initialized OBS client. ```javascript function getBucketStorageInfo(){ var bucketName = document.getElementById('bucketname').value; var obs = getObsClient(); obs.getBucketStorageInfo({ Bucket : bucketName }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Get bucket storageInfo:'); console.log('\tsize:' + result.InterfaceResult.Size); console.log('\tobjectNumber:' + result.InterfaceResult.ObjectNumber); console.log('\n'); } }); } ``` -------------------------------- ### List Objects by Page using OBS SDK for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/list-objects-sample.html This function lists objects in a bucket page by page, using pagination parameters like 'MaxKeys' and 'Marker'. It first ensures objects are inserted using `doInsert`, then recursively calls `listAll` to fetch all pages of objects. This method is useful for handling large numbers of objects efficiently. ```javascript function listObjectsByPage(){ var bucketName = document.getElementById('bucketname').value; var obs = getObsClient(); doInsert(obs, bucketName, function(){ function listAll(nextMarker, pageSize, pageIndex){ obs.listObjects({ Bucket: bucketName, MaxKeys: pageSize, Marker:nextMarker }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Page:' + pageIndex + '\n'); var j=0; for(;j' + result.InterfaceResult.Contents[j]['Key']); console.log('\tETag-->' + result.InterfaceResult.Contents[j]['ETag']); } console.log('\n'); if(result.InterfaceResult.IsTruncated === 'true'){ listAll(result.InterfaceResult.NextMarker, pageSize, pageIndex + 1); } } }); } listAll(null, 20, 1) }); } ``` -------------------------------- ### Get Object Content using BrowserJS SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/object-operations-sample.html Fetches the content of an object from an OBS bucket. It takes the bucket name and object key from HTML input fields and uses the `getObject` method to retrieve the object's data. ```javascript /* * Get object */ function getObject(){ var bucketName = document.getElementById('bucketname').value; var objectKey = document.getElementById('objectkey').value; var obs = getObsClient(); obs.getObject({ Bucket: bucketName, Key : objectKey }).then(function(result){ if(result.CommonMsg.Status < 300){ console.log('Get object content'); console.log('\tContent-->' + result.InterfaceResult.Content); console.log('\n'); } }); } ``` -------------------------------- ### Initialize ObsClient for BrowserJS SDK Source: https://context7.com/huaweicloud/huaweicloud-sdk-browserjs-obs/llms.txt Initializes the ObsClient with access credentials and server configuration. Supports basic and advanced configurations including timeouts, signature versions, and security settings. The client instance is used for all subsequent OBS operations. ```javascript const obsClient = new ObsClient({ access_key_id: 'YOUR_ACCESS_KEY_ID', secret_access_key: 'YOUR_SECRET_ACCESS_KEY', server: 'https://obs.your-region.example.com' }); ``` ```javascript const obsClient = new ObsClient({ access_key_id: 'YOUR_ACCESS_KEY_ID', secret_access_key: 'YOUR_SECRET_ACCESS_KEY', server: 'https://obs.your-region.example.com', timeout: 300000, signature: 'v4', security_token: null, is_secure: true, port: 443, path_style: false, region: 'your-region', is_cname: false }); ``` -------------------------------- ### Get Bucket Storage Info using JavaScript Source: https://context7.com/huaweicloud/huaweicloud-sdk-browserjs-obs/llms.txt Retrieves storage statistics for an OBS bucket, including total size and object count. This is useful for monitoring storage consumption and billing. It requires the bucket name as input and returns size in bytes and object count. ```javascript const bucketName = 'my-bucket'; obsClient.getBucketStorageInfo({ Bucket: bucketName }).then(function(result) { if (result.CommonMsg.Status < 300) { const sizeGB = (result.InterfaceResult.Size / (1024 * 1024 * 1024)).toFixed(2); console.log('Bucket storage information:'); console.log('Bucket:', bucketName); console.log('Size:', result.InterfaceResult.Size, 'bytes'); console.log('Size (GB):', sizeGB); console.log('Object Count:', result.InterfaceResult.ObjectNumber); } else { console.error('Get storage info failed:', result.CommonMsg.Message); } }).catch(function(error) { console.error('Error:', error); }); ``` -------------------------------- ### Manage Object ACL using BrowserJS SDK Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/object-operations-sample.html Performs operations to set and get the Access Control List (ACL) for an OBS object. This function allows setting the ACL to public read and then retrieves the current ACL settings, including owner and grants. ```javascript /* * Put/Get object acl operations */ function doObjectAcl(){ var bucketName = document.getElementById('bucketname').value; var objectKey = document.getElementById('objectkey').value; var obs = getObsClient(); obs.setObjectAcl({ Bucket: bucketName, Key: objectKey, ACL : obs.enums.AclPublicRead }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Set object ACL to ' + obs.enums.AclPublicRead + ' finished. \n'); obs.getObjectAcl({ Bucket: bucketName, Key: objectKey }).then(function(result) { console.log('Get object ACL:'); console.log('\tOwner[ID]-->' + result.InterfaceResult.Owner.ID); console.log('\tOwner[Name]-->' + result.InterfaceResult.Owner.Name); console.log('\tGrants:'); var i=0; for(;i' + result.InterfaceResult.Grants[i]['Grantee']['ID']); console.log('\tGrantee[Name]-->' + result.InterfaceResult.Grants[i]['Grantee']['Name']); console.log('\tGrantee[URI]-->' + result.InterfaceResult.Grants[i]['Grantee']['URI']); console.log('\tPermission-->' + result.InterfaceResult.Grants[i]['Permission']); } console.log('\n'); }); } }); } ``` -------------------------------- ### Insert Objects for Demonstration using OBS SDK for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/list-objects-sample.html This function inserts up to 100 objects into a specified bucket for demonstration purposes. Each object is named with a prefix followed by an index. It logs the success of each object insertion and indicates when the process is complete. This function is typically called before listing or deleting objects. ```javascript function doInsert(obs, bucketName, callback){ if(!inited){ var content = 'Hello OBS'; var finishedCount = 0; var objectCount = 100; var i=0; for(;i' + result.InterfaceResult.IndexDocument['Suffix']); console.log('\tErrorDocument[Key]-->' + result.InterfaceResult.ErrorDocument['Key']); console.log('\n'); obs.deleteBucketWebsite({ Bucket : bucketName }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Delete bucket website finished.\n'); console.log('\n'); } }); } }); } }); } ``` -------------------------------- ### Manage Bucket Versioning using OBS SDK for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/bucket-operations-sample.html Enables and retrieves the versioning status of an OBS bucket. It first gets the current status, then enables versioning if it's not already enabled, and finally retrieves the updated status. Requires bucket name and an OBS client. ```javascript function doBucketVersioning(){ var bucketName = document.getElementById('bucketname').value; var obs = getObsClient(); obs.getBucketVersioning({ Bucket : bucketName }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Default bucket versioning config ' + result.InterfaceResult.VersionStatus + '\n'); obs.setBucketVersioning({ Bucket : bucketName, VersionStatus : 'Enabled' }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('Enable bucket versioning finished.' + '\n'); obs.getBucketVersioning({ Bucket : bucketName }).then(function(result) { console.log('Current bucket versioning config ' + result.InterfaceResult.VersionStatus + '\n'); }); } }); } }); } ``` -------------------------------- ### List Objects with Default Parameters using OBS SDK for BrowserJS Source: https://github.com/huaweicloud/huaweicloud-sdk-browserjs-obs/blob/master/examples/list-objects-sample.html This function lists objects in a bucket using the default parameters of the `listObjects` method. By default, it will return up to 1000 objects. It first calls `doInsert` to ensure there are objects to list and then logs the key and ETag of each object found. ```javascript function listObjects(){ var bucketName = document.getElementById('bucketname').value; var obs = getObsClient(); doInsert(obs, bucketName, function(){ obs.listObjects({ Bucket: bucketName }).then(function(result) { if(result.CommonMsg.Status < 300){ console.log('List objects using default parameters:\n'); var j=0; for(;j' + result.InterfaceResult.Contents[j]['Key']); console.log('\tETag-->' + result.InterfaceResult.Contents[j]['ETag']); } console.log('\n'); } }); }); } ```