ali-oss JavaScript SDK

repository·master·Indexed 24 days ago

https://github.com/ali-sdk/ali-oss

The official JavaScript SDK for Aliyun Object Storage Service (OSS), supporting Node.js (>= 8.0.0) and browser environments. It provides a comprehensive API for managing buckets, objects, RTMP channels, and image processing services, with support for STS temporary credentials, V4 signatures, and automatic token refreshing.

Tokens
30.4K
Snippets
59
Records
98
Agent score
85%

What's inside ali-oss

  1. Use Cluster Mode for object operations

    master

    Cluster mode allows you to manage multiple OSS clients across different hosts. It currently only supports object operations.

    Configuration

    Initialize using ClusterClient from ali-oss. You provide an array of client configurations and a schedule strategy.

    Scheduling Strategies

    • roundRobin: The default strategy.
    • masterSlave: Routes requests to a master or slave based on the operation type.

    Supported Methods

    Get Methods (Uses the schedule to choose an available client):

    • client.get()
    • client.head()
    • client.getStream()
    • client.list()
    • client.signatureUrl()
    • client.chooseAvailable()
    • client.getACL()

    Put Methods (Executes the operation on ALL clients in the cluster):

    • client.put()
    • client.putStream()
    • client.delete()
    • client.deleteMulti()
    • client.copy()
    • client.putMeta()
    • client.putACL()
    • client.restore()
    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!');
    });
  2. Understand OSS error responses

    master

    Every error returned by the OSS server contains the following properties:

    • name {String}: The error name.
    • message {String}: The error message.
    • requestId {String}: A unique UUID for the request. If you encounter unhandled problems, provide this ID to OSS engineers for debugging.
    • hostId {String}: The name of the OSS cluster that handled the request.
  3. Abort or Cancel a multipartUpload

    master

    You can stop an ongoing multipart upload using two different mechanisms:

    1. Abort (abortMultipartUpload)

    Use this to permanently stop an upload. You must capture the checkpoint from the progress callback to get the name and uploadId. When an upload is aborted, the promise will catch an error with err.name === 'abort'.

    2. Cancel (cancel)

    Use this to cancel the upload via the client instance. To detect if an upload was cancelled, check store.isCancel() within the catch block.

    Note: Both abort and cancel support Node.js and Browser environments.

    // --- Abort Example ---
    let abortCheckpoint;
    store.multipartUpload('object', '/tmp/file', {
      progress: function (p, cpt, res) {
        abortCheckpoint = cpt;
      }
    }).then(res => {
      // success
    }).catch(err => {
      if (err.name === 'abort') {
        console.log('error: ', err.message)
      }
    });
    
    // Trigger abort
    store.abortMultipartUpload(abortCheckpoint.name, abortCheckpoint.uploadId);
    
    // --- Cancel Example ---
    try {
      await store.multipartUpload('object', '/tmp/file', {
        progress: (p, cpt, res) => {}
      });
    } catch (err) {
      if (store.isCancel()) {
        console.log('Upload was cancelled');
      }
    }
    
    // Trigger cancel (must use same client instance)
    store.cancel();
  4. Setup and Run the OSS Browser Example

    master

    To run the browser-side OSS example, follow these steps:

    1. Configure Application Settings: In main.js, set your bucket name and region:

      var bucket = '<your bucket name>';
      var region = 'oss-cn-hangzhou';
    2. Start the Server: Run the following command, replacing the placeholders with your STS credentials. Ensure port 9000 is not currently in use:

      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
    3. Access the App: Open http://localhost:3000 in your browser.

    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
  5. Configure CORS for OSS Form Post

    master

    When a browser performs a direct form POST to OSS, it includes an Origin header. You must configure Cross-Origin Resource Sharing (CORS) rules on your OSS bucket to allow these requests.

    Steps to configure in the OSS Management Console:

    1. Log in to the OSS Management Console.
    2. Select your target bucket from the list.
    3. Navigate to the Basic Settings (基础设置) tab.
    4. Find the CORS Settings (跨域设置) section and click Settings (设置).
    5. Click Create Rule (创建规则) to allow the POST method and the appropriate Origin headers.
  6. Configure the Application Server for Form Post

    master

    To set up the server-side component that generates signatures, you must configure your OSS credentials and bucket information in the server source code.

    1. Open example/server/postObject.js.
    2. Update the config object with your credentials:
    const config = {
      accessKeyId: '<yourAccessKeyId>',  // Your AccessKey ID
      accessKeySecret: '<yourAccessKeySecret>', // Your AccessKey Secret
      bucket: '<bucket-name>' // Your OSS Bucket name
    }
    1. If you are using STS (Security Token Service) for temporary authorization, you must also configure the STS_ROLE:
    const STS_ROLE = '<STS_ROLE>';
    1. Install dependencies and start the server:
    npm install
    node postObject.js
    const config = {
      accessKeyId: '<yourAccessKeyId>',  //
      accessKeySecret: '<yourAccessKeySecret>', //
      bucket: '<bucket-name>'
    }
    
    const STS_ROLE = '<STS_ROLE>';
  7. Initialize the client without OSS.Wrapper (5.x to 6.x)

    master

    In version 6.x, OSS.Wrapper has been removed. The standard new OSS() constructor now returns a Promise-based client, providing the same functionality as the previous OSS.Wrapper. You should update your client initialization to use new OSS() directly.

    const OSS = require('ali-oss');
    
    // 6.x usage: use new OSS() instead of new OSS.Wrapper()
    const client = new OSS({
      accessKeyId: xxx,
      accessKeySecret: xxx,
      region: xxx,
      bucket: bucketName
    });
    
    client.operation(...).then(...).catch(...);
  8. Migrate bucket operations by removing the region parameter (5.x to 6.x)

    master

    When upgrading from version 5.x to 6.x, all bucket operations no longer require the region parameter. This applies to methods such as putBucket, deleteBucket, getBucketInfo, getBucketLocation, putBucketACL, getBucketACL, putBucketLogging, getBucketLogging, deleteBucketLogging, putBucketWebsite, getBucketWebsite, deleteBucketWebsite, putBucketReferer, and getBucketReferer.

    Old pattern (5.x): Client.deleteBucket(bucket, region);

    New pattern (6.x): Client.deleteBucket(bucket);

    const OSS = require('ali-oss');
    
    const Client = new OSS(...);
    
    // 6.x usage: remove the second 'region' argument
    Client.deleteBucket(bucket);
  9. Use ali-oss in the Browser

    master

    You can use most ali-oss functionalities in the browser, but note the following limitations and requirements:

    Limitations

    • Streaming Uploads: put with streaming does not support chunked encoding; it uses multipart upload instead.
    • Local File Downloads: Direct file system manipulation is not possible; use signed object URLs for downloading.
    • Bucket Operations: Operations like listBuckets or putBucketLogging will fail because the OSS server does not currently support CORS for bucket-level operations.

    Setup Requirements

    1. CORS Configuration

    To allow browser-side JavaScript to interact with your bucket, you must configure CORS rules on your OSS bucket:

    • Allowed Origins: * (or your specific domain)
    • Allowed Methods: PUT, GET, POST, DELETE, HEAD
    • Allowed Headers: *
    • Exposed Headers: ETag

    2. Security (STS)

    To avoid exposing your permanent accessKeyId and accessKeySecret in client-side code, use STS (Security Token Service) to grant temporary access.

    3. Browser Compatibility

    • Supported: IE >= 10, Edge, major versions of Chrome, Firefox, Safari, Android, iOS, and WP.
    • Note: For browsers that do not support Promises (like IE10/11), you must provide a promise-polyfill.
    <!-- Introducing online resources -->
    <script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-x.x.x.min.js"></script>
    <!-- Introducing offline resources -->
    <script src="./aliyun-oss-sdk-x.x.x.min.js"></script>
    
    <script type="text/javascript">
      const store = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: '<access-key-id>',
        accessKeySecret: '<access-key-secret>',
        bucket: '<bucket-name>',
        stsToken: '<security-token'
      });
    
      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());
        });
    </script>
  10. Implement Form Post Upload to OSS

    master

    This method allows a client to upload files directly to OSS using a form POST request. To prevent exposing sensitive credentials, the process follows this workflow:

    1. The Application Server generates a signature using accessKeyId and accessKeySecret (or via STS temporary authorization).
    2. The Client requests this signature from the application server.
    3. The Client performs a direct POST request to OSS using the signature and the file data.

    Prerequisites

    • The application server domain must be accessible via the public internet.
    • Node.js version 8.x or higher must be installed on the server.
    • A browser with JavaScript support.