### Install ali-oss SDK Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Installs the ali-oss SDK using npm. This is the first step to integrate the SDK into your Node.js project. ```bash npm install ali-oss --save ``` -------------------------------- ### Download File from Ali OSS using Go Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides an example of downloading a file from an Alibaba Cloud OSS bucket using the Go SDK. It shows how to get the OSS client, specify the bucket and object, and download the file to a local path. ```Go package main import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // Replace with your actual endpoint, accessKeyId, and accessKeySecret endpoint := "your-oss-endpoint" accessKeyId := "your-access-key-id" accessKeySecret := "your-access-key-secret" bucketName := "your-bucket-name" objectName := "your-object-name" downloadFilePath := "path/to/save/downloaded/file" // Initialize OSS client client, err := oss.New(endpoint, accessKeyId, accessKeySecret) if err != nil { fmt.Println("Error initializing OSS client:", err) return } // Get bucket handler bucket, err := client.Bucket(bucketName) if err != nil { fmt.Println("Error getting bucket handler:", err) return } // Download file err = bucket.GetObjectToFile(objectName, downloadFilePath) if err != nil { fmt.Println("Error downloading file:", err) return } fmt.Printf("Successfully downloaded %s/%s to %s\n", bucketName, objectName, downloadFilePath) } ``` -------------------------------- ### ali-oss multipartUploadCopy Example Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Demonstrates how to use the multipartUploadCopy function to copy an object with specified source details. Includes examples for basic copying and copying with options like parallel uploads, part size, and a progress callback. ```JavaScript const result = await store.multipartUploadCopy('object', { sourceKey: 'sourceKey', sourceBucketName: 'sourceBucketName' }); let savedCpt; console.log(result); ``` ```JavaScript const result = await store.multipartUploadCopy( 'object', { sourceKey: 'sourceKey', sourceBucketName: 'sourceBucketName' }, { parallel: 4, partSize: 1024 * 1024, progress: function (p, cpt, res) { console.log(p); savedCpt = cpt; console.log(cpt); console.log(res.headers['x-oss-request-id']); } } ); console.log(result); ``` ```JavaScript const result = await store.multipartUploadCopy( 'object', { sourceKey: 'sourceKey', sourceBucketName: 'sourceBucketName' }, { checkpoint: savedCpt, progress: function (p, cpt, res) { console.log(p); console.log(cpt); console.log(res.headers['x-oss-request-id']); } } ); console.log(result); ``` -------------------------------- ### Download File from Ali OSS using Node.js Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides an example of downloading a file from an Alibaba Cloud OSS bucket using the Node.js SDK. This involves initializing the OSS client and then using the `get` method to retrieve the object, specifying the object name and the local destination path. ```JavaScript const OSS = require('ali-oss'); async function downloadFile(bucketName, objectName, destinationPath) { const client = new OSS({ region: 'your-region', accessKeyId: 'your-access-key-id', accessKeySecret: 'your-access-key-secret', bucket: bucketName }); try { const result = await client.get(objectName, destinationPath); console.log('File downloaded successfully:', result); } catch (err) { console.error('Error downloading file:', err); } } // Example usage: // downloadFile('your-bucket-name', 'your-object-name.txt', '/path/to/save/downloaded/file.txt'); ``` -------------------------------- ### Install ali-oss SDK Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md This snippet shows how to install the ali-oss SDK using npm, which is the standard package manager for Node.js. This command adds the SDK as a dependency to your project. ```bash npm install ali-oss --save ``` -------------------------------- ### Upload File in Java Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides a Java code example for uploading a file to an OSS bucket. It shows how to get the bucket, create an input stream for the file, and upload it. ```Java import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.PutObjectRequest; import java.io.File; public class UploadFile { public static void main(String[] args) { // Endpoint should be the endpoint of your bucket. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // Your access key ID and secret String accessKeyId = ""; String accessKeySecret = ""; // Bucket name String bucketName = "my-bucket-name"; // File path String filePath = "./local-file.txt"; // Object name String objectName = "my-object-name.txt"; // Construct a OSSClient instance OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); try { // Create a PutObjectRequest PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath)); // Upload file ossClient.putObject(putObjectRequest); System.out.println("File uploaded successfully."); } catch (Exception e) { e.printStackTrace(); } finally { // Shut down the client ossClient.shutdown(); } } } ``` -------------------------------- ### List Objects After a Specific Key with Ali OSS SDK Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md This example illustrates how to list objects in a directory ('a/') starting after a specific object key ('a/b'), excluding 'a/b' itself. It uses 'delimiter', 'prefix', and 'start-after' parameters. ```javascript const result = await store.listV2({ delimiter: '/', prefix: 'a/', 'start-after': 'a/b' }); console.log(result.objects); ``` -------------------------------- ### Initialize OSS with Accelerate Endpoint Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to configure the ali-oss instance to use an accelerate endpoint for faster data transfer. It includes examples for global and overseas accelerate endpoints. ```javascript const OSS = require('ali-oss'); const store = new OSS({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', endpoint: 'oss-accelerate.aliyuncs.com' }); ``` -------------------------------- ### Create Bucket (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Provides an example of creating a new bucket in Ali OSS using the Node.js SDK. You need to specify the bucket name and optionally other configurations. ```JavaScript async function createBucketInstance(bucketName) { try { let result = await client.putBucket(bucketName); console.log(`Bucket '${bucketName}' created successfully.`); } catch (err) { console.error(`Error creating bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Upload File to OSS (Go) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides a Go code example for uploading a file to an Alibaba Cloud OSS bucket. It requires the bucket name, object key, and the local file path. ```Go package main import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // ... (OSS client initialization as above) // Bucket name bucketName := "your-bucket-name" // Object name objectName := "your-object-name" // Local file path filePath := "path/to/your/local/file.txt" // Get bucket object bucket, err := client.Bucket(bucketName) if err != nil { fmt.Printf("Error getting bucket: %v\n", err) return } // Upload file err = bucket.PutObjectFromFile(objectName, filePath) if err != nil { fmt.Printf("Error uploading file: %v\n", err) return } fmt.Printf("File '%s' uploaded successfully to bucket '%s' as '%s'.\n", filePath, bucketName, objectName) } ``` -------------------------------- ### Set Bucket Website Configuration (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Provides an example of configuring a bucket to serve static website content using the Node.js SDK. This includes specifying index and error documents. ```JavaScript async function setBucketWebsiteConfig(bucketName, indexDoc, errorDoc) { const config = { index: indexDoc, error: errorDoc }; try { let result = await client.putBucketWebsite(bucketName, config); console.log(`Website configuration set for bucket '${bucketName}'.`); } catch (err) { console.error(`Error setting website config for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Download File from Ali OSS (Go) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides a Go code example for downloading a file from Ali OSS. The code specifies the object key and the local file path for saving the downloaded content. ```Go import ( "github.com/aliyun/aliyun-oss-go-sdk/oss" ) // create client client, err := oss.New(endpoint, accessKeyId, accessKeySecret) // handle error // get bucket bucket, err := client.Bucket(bucketName) // handle error // download file err = bucket.GetObjectToFile(objectName, localFilePath) // handle error ``` -------------------------------- ### Download Object from Ali OSS Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides code examples for downloading an object from an Alibaba Cloud OSS bucket. This requires specifying the bucket name, object key, and the local path where the file will be saved. ```Python from oss2 import Auth, Bucket # Your endpoint, access key ID, and secret endpoint = 'http://oss-cn-hangzhou.aliyuncs.com' access_key_id = 'YOUR_ACCESS_KEY_ID' access_key_secret = 'YOUR_ACCESS_KEY_SECRET' # Bucket name bucket_name = 'your-bucket-name' # Object key (file name in the bucket) object_key = 'your-object-key' # Local file path to save the downloaded file local_file_path = 'path/to/save/downloaded_file.txt' # Authenticate auth = Auth(access_key_id, access_key_secret) # Get bucket object bucket = Bucket(auth, endpoint, bucket_name) try: # Download file bucket.get_object_to_file(object_key, local_file_path) print(f"File '{object_key}' downloaded successfully to '{local_file_path}'") except Exception as e: print(f"Error downloading file: {e}") ``` -------------------------------- ### Set Bucket Logging (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Provides an example of configuring server access logging for a bucket using the Node.js SDK. You need to specify a prefix for the log files. ```JavaScript async function setBucketServerLogging(bucketName, logPrefix) { try { let result = await client.putBucketLogging(bucketName, logPrefix); console.log(`Logging enabled for bucket '${bucketName}' with prefix '${logPrefix}'.`); } catch (err) { console.error(`Error setting logging for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Initiate Bucket WORM (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Provides an example of initiating a Write Once, Read Many (WORM) protection for a bucket using the Node.js SDK. This is used for compliance and data immutability. ```JavaScript async function initiateBucketWormProtection(bucketName, retentionDays) { try { let result = await client.initiateBucketWorm(bucketName, retentionDays); console.log(`WORM protection initiated for bucket '${bucketName}' with ${retentionDays} days retention.`); } catch (err) { console.error(`Error initiating WORM protection for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Get Bucket Location (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Provides an example of retrieving the geographical region where a bucket is located using the Node.js SDK. ```JavaScript async function getBucketLocationInfo(bucketName) { try { let result = await client.getBucketLocation(bucketName); console.log(`Bucket '${bucketName}' location: ${result.location}`); } catch (err) { console.error(`Error getting location for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Ali-OSS SDK Initialization and Basic Operations Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Demonstrates how to initialize the Ali-OSS SDK and perform basic operations such as creating buckets and uploading files. This snippet covers essential setup and common use cases for interacting with Ali-OSS. ```JavaScript const OSS = require('ali-oss'); async function main() { // Initialize OSS client const client = new OSS({ region: 'your-region', accessKeyId: 'your-access-key-id', accessKeySecret: 'your-access-key-secret', bucket: 'your-bucket-name' }); try { // Create a bucket (if it doesn't exist) await client.putBucket('your-new-bucket-name'); console.log('Bucket created successfully.'); // Upload a file const result = await client.put('your-object-key', 'path/to/your/local/file.txt'); console.log('File uploaded successfully:', result); } catch (err) { console.error('Error:', err); } } main(); ``` -------------------------------- ### Initialize OSS with Basic Credentials Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Demonstrates the basic usage of the ali-oss library by creating an OSS instance with access key ID, access key secret, bucket name, and region. ```javascript const OSS = require('ali-oss'); const store = new OSS({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou' }); ``` -------------------------------- ### Create Bucket in Go Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Demonstrates how to create an OSS bucket using the Go SDK. This involves initializing the client and calling the create bucket method. ```Go package main import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // Your AccessKeyId and AccessKeySecret. // "", "" client, err := oss.New("oss-cn-hangzhou.aliyuncs.com", "", "") if err != nil { panic(err) } // Specify the bucket name. bucketName := "my-bucket-name" // Create the bucket. err = client.CreateBucket(bucketName) if err != nil { panic(err) } fmt.Printf("Bucket %s created successfully\n", bucketName) } ``` -------------------------------- ### Get Object Metadata from Ali OSS Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides an example of retrieving metadata for an object stored in Ali OSS. This includes information like content type, size, and last modified date. ```C# GetObjectMetadataRequest request = new GetObjectMetadataRequest(bucketName, objectKey); ``` -------------------------------- ### Download File from Ali OSS (Java) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides a Java code example for downloading a file from Ali OSS. This process requires specifying the bucket, object key, and the local path where the file will be saved. ```Java OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); // download file ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFilePath)); // close client ossClient.shutdown(); ``` -------------------------------- ### Initialize OSS Client (Go) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Shows how to initialize the OSS client in Go using your endpoint, access key ID, and access key secret. This is the first step for interacting with OSS. ```Go package main import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // Endpoint endpoint := "http://oss-cn-hangzhou.aliyuncs.com" // AccessKeyId accessKeyId := "YOUR-ACCESSKEYID" // AccessKeySecret accessKeySecret := "YOUR-ACCESSKEYSECRET" // Create client client, err := oss.New(endpoint, accessKeyId, accessKeySecret) if err != nil { fmt.Printf("Error creating OSS client: %v\n", err) return } fmt.Println("OSS client initialized successfully.") } ``` -------------------------------- ### Get Bucket Versions with Version ID and Key Markers Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Fetches object versions starting from a specified version ID marker and key marker. This allows for precise control over the version history retrieval. ```javascript const result = await store.getBucketVersions({ versionIdMarker: 'versionIdMarker', keyMarker: 'keyMarker' }); console.log(result.objects); console.log(result.deleteMarker); ``` -------------------------------- ### Initialize Ali OSS Client (Go) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Shows how to initialize the Ali OSS client in Go using your AccessKey ID, AccessKey Secret, and endpoint. ```Go package main import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // Your AccessKeyId and AccessKeySecret accessKeyId := "YOUR_ACCESS_KEY_ID" accessKeySecret := "YOUR_ACCESS_KEY_SECRET" // Your endpoint endpoint := "YOUR_ENDPOINT" // Create a bucket manager instance client, err := oss.New(endpoint, accessKeyId, accessKeySecret) if err != nil { fmt.Println("Error creating OSS client: ", err) return } fmt.Println("OSS client initialized successfully.") } ``` -------------------------------- ### Upload File to OSS (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides a Node.js code example for uploading a file to an Alibaba Cloud OSS bucket. It requires the bucket name, object key, and the local file path. ```JavaScript const OSS = require('ali-oss'); // ... (OSS client initialization as above) // Bucket name const bucketName = 'your-bucket-name'; // Object name const objectName = 'your-object-name'; // Local file path const filePath = 'path/to/your/local/file.txt'; async function uploadFile() { try { const result = await client.put(objectName, filePath); console.log('Upload result:', result); } catch (err) { console.error('Error uploading file:', err); } } uploadFile(); ``` -------------------------------- ### Initialize OSS with V4 Signature Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Demonstrates how to initialize the ali-oss instance with V4 signature support and retrieve bucket information. ```javascript const OSS = require('ali-oss'); const store = new OSS({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou', authorizationV4: true }); try { const bucketInfo = await store.getBucketInfo('your bucket name'); console.log(bucketInfo); } catch (e) { ``` -------------------------------- ### Initialize Ali OSS Client Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Demonstrates how to initialize the Ali OSS client with endpoint and credentials. This is a fundamental step before performing any operations. ```Java import com.aliyun.oss.OSSClient; // Your AccessKeyId and AccessKeySecret String accessKeyId = "YOUR_ACCESS_KEY_ID"; String accessKeySecret = "YOUR_ACCESS_KEY_SECRET"; // Your endpoint String endpoint = "YOUR_ENDPOINT"; // Bucket name String bucketName = "YOUR_BUCKET_NAME"; // Construct a OSSClient instance OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); ``` -------------------------------- ### Get Live Channel History - JavaScript Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Retrieves the history of a live channel using its ID. It can optionally accept a timeout for the operation. The response includes pushing records with start time, end time, and remote address, along with response information. ```JavaScript const cid = 'my-channel'; const r = await this.store.getChannelHistory(cid); console.log(r); ``` -------------------------------- ### Download File from Ali OSS using Node.js Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides an example of downloading a file from an Ali OSS bucket using the Node.js SDK. You'll need to configure the OSS client and then use the `get` method, specifying the object key and the local path where the file should be saved. ```Node.js const OSS = require('ali-oss'); async function downloadFile(bucketName, objectKey, localPath) { const client = new OSS({ region: 'your-region', accessKeyId: 'your-access-key-id', accessKeySecret: 'your-access-key-secret', bucket: bucketName, }); try { const result = await client.get(objectKey, localPath); console.log('Download successful:', result); } catch (err) { console.error('Download failed:', err); } } // Example usage: // downloadFile('your-bucket-name', 'your-object-key', '/path/to/save/downloaded/file.txt'); ``` -------------------------------- ### Initialize Ali OSS Client and Perform Operations (JavaScript/HTML) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md This snippet demonstrates how to include the Ali OSS SDK in an HTML file and use JavaScript to initialize the client with credentials and a bucket name. It then performs a sequence of operations: listing objects, uploading a file, and downloading it, logging the results to the console. ```html ``` ```javascript const store = new OSS({ region: 'oss-cn-hangzhou', accessKeyId: '', accessKeySecret: '', bucket: '', stsToken: '' }); store .list() .then(result => { console.log('objects: %j', result.objects); return store.put('my-obj', new OSS.Buffer('hello world')); }) .then(result => { console.log('put result: %j', result); return store.get('my-obj'); }) .then(result => { console.log('get result: %j', result.content.toString()); }); ``` -------------------------------- ### Create Ali OSS Live Channel Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Creates a live channel with specified configuration, including description, status, and target HLS settings. It returns publish and play URLs upon success. ```JavaScript const cid = 'my-channel'; const conf = { Description: 'this is channel 1', Status: 'enabled', Target: { Type: 'HLS', FragDuration: '10', FragCount: '5', PlaylistName: 'playlist.m3u8' } }; const r = await this.store.putChannel(cid, conf); console.log(r); ``` -------------------------------- ### Initialize Ali OSS Cluster Client Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Demonstrates how to initialize an Ali OSS Cluster client with multiple host configurations and a specified scheduling strategy (e.g., masterSlave). It also shows how to listen for error events and handle client readiness. ```javascript const Cluster = require('ali-oss').ClusterClient; const client = Cluster({ cluster: [ { host: 'host1', accessKeyId: 'id1', accessKeySecret: 'secret1' }, { host: 'host2', accessKeyId: 'id2', accessKeySecret: 'secret2' } ], schedule: 'masterSlave' //default is `roundRobin` }); // listen error event to logging error client.on('error', function (err) { console.error(err.stack); }); // client init ready client.ready(function () { console.log('cluster client init ready, go ahead!'); }); ``` -------------------------------- ### Initialize Ali OSS Client (Python) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Demonstrates initializing the Ali OSS client in Python using your AccessKey ID, AccessKey Secret, and endpoint. ```Python from oss2.models import Bucket from oss2 import Auth, Service # Your AccessKeyId and AccessKeySecret access_key_id = 'YOUR_ACCESS_KEY_ID' access_key_secret = 'YOUR_ACCESS_KEY_SECRET' # Your endpoint endpoint = 'YOUR_ENDPOINT' # Construct OSS client auth = Auth(access_key_id, access_key_secret) service = Service(auth, endpoint) print("OSS client initialized successfully.") ``` -------------------------------- ### Upload File to Ali OSS (Go) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Demonstrates uploading a file to Ali OSS using the Go SDK. This includes setting up the client and performing the upload operation. ```Go import ( "github.com/aliyun/aliyun-oss-go-sdk/oss" ) // create client client, err := oss.New(endpoint, accessKeyId, accessKeySecret) // handle error // get bucket bucket, err := client.Bucket(bucketName) // handle error // upload file err = bucket.PutObjectFromFile(objectName, localFilePath) // handle error ``` -------------------------------- ### Start STS App Server with Environment Variables Source: https://github.com/ali-sdk/ali-oss/blob/master/example/README.md This command demonstrates how to start the node-sts-app-server using cross-env to set necessary environment variables for STS credentials, including access key ID, secret, and role ARN. This is crucial for securely granting temporary access to OSS from the browser. ```Shell cross-env \ ALI_SDK_STS_ID={your sts accessKeyId} \ ALI_SDK_STS_SECRET={your sts accessKeySecret} \ ALI_SDK_STS_ROLE={your rolearn} \ npm run start ``` -------------------------------- ### Get Bucket Policy (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to retrieve the bucket policy for a bucket using the Node.js SDK. ```JavaScript async function getBucketPolicy(bucketName) { try { let result = await client.getBucketPolicy(bucketName); console.log(`Bucket policy for bucket '${bucketName}':`, result.policy); } catch (err) { console.error(`Error getting bucket policy for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Initialize Ali OSS Client (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Demonstrates how to initialize the Ali OSS client with configuration options for Node.js environments. This is the first step to interacting with Ali OSS services. ```JavaScript const OSS = require('ali-oss'); const client = new OSS({ region: 'your-region', accessKeyId: 'your-access-key-id', accessKeySecret: 'your-access-key-secret', bucket: 'your-bucket-name' }); ``` -------------------------------- ### Get Bucket Tags (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to retrieve the tags associated with a bucket using the Node.js SDK. ```JavaScript async function getBucketTags(bucketName) { try { let result = await client.getBucketTags(bucketName); console.log(`Tags for bucket '${bucketName}':`, result.tagging); } catch (err) { console.error(`Error getting tags for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Get Bucket CORS Configuration (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to retrieve the CORS configuration for a bucket using the Node.js SDK. ```JavaScript async function getBucketCORS(bucketName) { try { let result = await client.getBucketCORS(bucketName); console.log(`CORS config for bucket '${bucketName}':`, result.corsRules); } catch (err) { console.error(`Error getting CORS for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Get Bucket Website Configuration (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to retrieve the website configuration for a bucket using the Node.js SDK. ```JavaScript async function getBucketWebsiteConfig(bucketName) { try { let result = await client.getBucketWebsite(bucketName); console.log(`Website config for bucket '${bucketName}':`, result.websiteRules); } catch (err) { console.error(`Error getting website config for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Initialize OSS Client (PHP) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Shows how to initialize the OSS client in PHP using your endpoint, access key ID, and access key secret. This is the first step for interacting with OSS. ```PHP getMessage()); } ``` -------------------------------- ### Download File from Ali OSS (Go) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides a Go code example for downloading a file from an Ali OSS bucket. It requires the bucket name, object key, and the local path where the file will be saved. ```Go package main import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { // Your endpoint endpoint := "http://oss-cn-hangzhou.aliyuncs.com" // Your AccessKeyId accessKeyId := "YOUR-ACCESSKEYID" // Your AccessKeySecret accessKeySecret := "YOUR-ACCESSKEYSECRET" // Your bucket name bucketName := "your-bucket-name" // Object key objectKey := "your-object-key.txt" // Local file path to save localFilePath := "path/to/save/downloaded-file.txt" // New OSS client client, err := oss.New(endpoint, accessKeyId, accessKeySecret) if err != nil { fmt.Println("Error creating OSS client:", err) return } // Get bucket bucket, err := client.Bucket(bucketName) if err != nil { fmt.Println("Error getting bucket:", err) return } // Download file err = bucket.GetObjectToFile(objectKey, localFilePath) if err != nil { fmt.Println("Error downloading file:", err) return } fmt.Println("File downloaded successfully!") } ``` -------------------------------- ### Get Bucket ACL (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Demonstrates how to retrieve the current ACL settings for a bucket using the Node.js SDK. ```JavaScript async function getBucketAccessControl(bucketName) { try { let result = await client.getBucketACL(bucketName); console.log(`ACL for bucket '${bucketName}': ${result.acl}`); } catch (err) { console.error(`Error getting ACL for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Get Bucket Information from Ali OSS Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Demonstrates how to retrieve information about an Ali OSS bucket, such as its creation date and location. ```PHP $bucketInfo = $ossClient->getBucketInfo($bucketName); ``` -------------------------------- ### Get Bucket WORM Configuration (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to retrieve the WORM protection configuration for a bucket using the Node.js SDK. ```JavaScript async function getBucketWormConfig(bucketName) { try { let result = await client.getBucketWorm(bucketName); console.log(`WORM configuration for bucket '${bucketName}':`, result.wormConfig); } catch (err) { console.error(`Error getting WORM configuration for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Get Bucket Encryption Configuration (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to retrieve the server-side encryption configuration for a bucket using the Node.js SDK. ```JavaScript async function getBucketEncryption(bucketName) { try { let result = await client.getBucketEncryption(bucketName); console.log(`Encryption config for bucket '${bucketName}':`, result.encryptionRules); } catch (err) { console.error(`Error getting encryption for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Download Object with Ali OSS SDK Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides code examples for downloading an object from Ali OSS. This involves specifying the bucket name, object key, and the local path or stream to save the downloaded content. Ensure the Ali OSS SDK is correctly configured. ```Java OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFilePath)); ossClient.shutdown(); ``` ```Python from oss2.models import GetObjectResult bucket = Bucket(auth, endpoint, bucket_name) result = bucket.get_object('remote_file.txt') with open('local_downloaded.txt', 'wb') as filename: for chunk in result.chunks(32 * 1024): filename.write(chunk) ``` ```Go import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func downloadFile(bucket *oss.Bucket, objectKey string, localFile string) { err := bucket.Õ‹PutObjectFromFile(objectKey, localFile) if err != nil { fmt.Println("Error: " + err.Error()) return } fmt.Println("Download Success!") } ``` ```JavaScript const OSS = require('ali-oss'); async function downloadFile(client, bucketName, objectName, filePath) { try { let result = await client.get(objectName, filePath); console.log(result); } catch (err) { console.error(err); } } ``` ```PHP use OSS\OSS; use OSS\Core\OssException; try { $ossClient = OSS::singleton(); $ossClient->downloadFile($bucket, $objectKey, $filePath); } catch (OssException $e) { printf($e->getMessage() . "\n"); } ``` ```C# using Aliyun.OSS; using (var client = new OssClient(endpoint, accessKeyId, accessKeySecret)) { client.DownloadFile(bucketName, objectName, localFilePath); } ``` -------------------------------- ### Initialize Client without OSS.Wrapper (JavaScript) Source: https://github.com/ali-sdk/ali-oss/blob/master/UPGRADING.md This code snippet illustrates the updated method for initializing the Aliyun OSS client. The 'OSS.Wrapper' is no longer used; instead, clients are initialized directly with 'new OSS()', which now returns a Promise similar to the previous 'OSS.Wrapper'. ```javascript const OSS = require('ali-oss'); const client = new OSS({ accessKeyId: xxx, accessKeySecret: xxx, region: xxx, bucket: bucketName }) client.operation(...).then(...).catch(...); ``` -------------------------------- ### Get Bucket Referer Configuration (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to retrieve the referer protection configuration for a bucket using the Node.js SDK. ```JavaScript async function getBucketReferer(bucketName) { try { let result = await client.getBucketReferer(bucketName); console.log(`Referer config for bucket '${bucketName}':`, result.refererConfiguration); } catch (err) { console.error(`Error getting referer config for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Get Bucket Versioning Status (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to retrieve the versioning status (enabled or suspended) for a bucket using the Node.js SDK. ```JavaScript async function getBucketVersioningStatus(bucketName) { try { let result = await client.getBucketVersioning(bucketName); console.log(`Versioning status for bucket '${bucketName}':`, result.versioning); } catch (err) { console.error(`Error getting versioning status for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Initialize Ali OSS Client Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Demonstrates how to initialize the Ali OSS client with endpoint, access key ID, and access key secret. This is a fundamental step for all subsequent operations. ```Java OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); ``` -------------------------------- ### Get Bucket Lifecycle Rules (Node.js) Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Shows how to retrieve the lifecycle management rules configured for a bucket using the Node.js SDK. ```JavaScript async function getBucketLifecycleRules(bucketName) { try { let result = await client.getBucketLifecycle(bucketName); console.log(`Lifecycle rules for bucket '${bucketName}':`, result.rules); } catch (err) { console.error(`Error getting lifecycle rules for bucket '${bucketName}':`, err); } } ``` -------------------------------- ### Create Image Service Instance - JavaScript Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Initializes an Image Service instance for interacting with OSS image functionalities. It requires `accessKeyId`, `accessKeySecret`, `bucket`, and `imageHost`. Optional parameters include `region`, `internal` network access, and a default `timeout`. ```JavaScript const oss = require('ali-oss'); const imgClient = oss.ImageClient({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'my_image_bucket', imageHost: 'thumbnail.myimageservice.com' }); ``` -------------------------------- ### Delete Object in PHP Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides a PHP example for deleting an object from an OSS bucket. It demonstrates how to initialize the client and use the deleteObject method. ```PHP '; $accessKeySecret = ''; $endpoint = 'oss-cn-hangzhou.aliyuncs.com'; $bucket = 'my-bucket-name'; $object = 'my-object-name.txt'; try { $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint); $ossClient->deleteObject($bucket, $object); echo "Object '$object' deleted successfully."; } catch (OssException $e) { printf($e->getMessage() . "\n"); } ``` -------------------------------- ### Get Object Tags with ali-oss Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Obtains the tags associated with an object in ali-oss. This function can optionally accept a version ID for historical objects. ```javascript // .getObjectTagging(name[, options]) // parameters: // - name {String} the object name // - [options] {Object} optional args // - [versionId] {String} the version id of history object // Success will return the channel information. // object: // - tag {Object} the tag of object // - res {Object} response info ``` -------------------------------- ### Initialize OSS with Custom Domain Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Illustrates how to use a custom domain name to access OSS by setting the 'cname' option to true and providing the custom domain in the 'endpoint' field. ```javascript const OSS = require('ali-oss'); const store = new OSS({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', cname: true, endpoint: 'your custome domain' }); ``` -------------------------------- ### Download Object from Ali OSS Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Provides examples for downloading an object from Alibaba Cloud OSS. This process requires the bucket name, object key, and a destination path or method to handle the downloaded content. Ensure proper authentication and permissions are set. ```javascript const OSS = require('ali-oss'); async function downloadFile(bucketName, objectKey, destinationPath) { const client = new OSS({ region: 'your-region', accessKeyId: 'your-access-key-id', accessKeySecret: 'your-access-key-secret', bucket: bucketName }); try { const result = await client.get(objectKey); // result.content contains the file content as a Buffer // You can save it to a file or process it further console.log('Download successful. Content length:', result.content.length); // Example: saving to a file // require('fs').writeFileSync(destinationPath, result.content); } catch (err) { console.error('Download failed:', err); } } // Example usage: // downloadFile('your-bucket-name', 'your-object-key', '/path/to/save/file.txt'); ``` -------------------------------- ### Get Bucket Versions with Key Marker Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Lists object versions from a specific key marker in the bucket. This is useful for paginating through version history. ```javascript const result = await store.getBucketVersions({ keyMarker: 'keyMarker' }); console.log(result.objects); ``` -------------------------------- ### Get Ali OSS Bucket ACL Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Retrieves the Access Control List (ACL) settings for a specified bucket. An optional timeout can be provided. ```JavaScript store.getBucketACL('helloworld').then(result => { console.log(result.acl); }); ``` -------------------------------- ### Initialize Ali OSS Client (Java) Source: https://github.com/ali-sdk/ali-oss/blob/master/example/src/template/index.html Demonstrates how to initialize the Ali OSS client in Java. This is a fundamental step for any interaction with the OSS service. It requires endpoint and credentials. ```Java import com.aliyun.oss.OSSClient; // Endpoint String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // Access key ID String accessKeyId = "YOUR-ACCESSKEYID"; // Access key secret String accessKeySecret = "YOUR-ACCESSKEYSECRET"; // Construct a OSSClient instance OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); ``` -------------------------------- ### Get Ali OSS Bucket Location Source: https://github.com/ali-sdk/ali-oss/blob/master/README.md Retrieves the geographical location of a specified bucket. Uses a default bucket name if none is provided. ```JavaScript store.getBucketLocation('helloworld').then(res => { console.log(res.location); }); ```