All Products
Search
Document Center

Object Storage Service:Installation

Last Updated:Dec 26, 2023

OSS SDK for Browser.js allows you to programmatically manage resources in Object Storage Service (OSS). For example, you can manage buckets, upload objects, download objects, and process images. This topic describes how to install and use OSS SDK for Browser.js.

Prerequisites

  • A Resource Access Management (RAM) user or temporary access credentials are created in Security Token Service (STS) to access OSS.

    The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Therefore, we recommend that you follow the best practices of Alibaba Cloud for security. If you deploy your service on the server, you can use a RAM user or temporary access credentials to call API operations or perform routine O&M. If you deploy your service on the client, use temporary access credentials to call API operations. For more information, see Overview.

  • Cross-origin resource sharing (CORS) rules are configured.

    To access OSS by using a browser, configure a CORS rule based on the following requirements:

    • Source: Specify a complete origin URL (example: https://www.aliyun.com) or specify a URL that contains an asterisk (*) wildcard character (example: https://*.aliyun.com).

    • Allowed Methods: Select the methods based on your requirements. For example, you can select PUT to perform multipart upload and select DELETE to delete objects.

    • Allowed Headers: Set the value to *.

    • Exposed Headers: Set the values to ETag, x-oss-request-id, and x-oss-version-id.

    image.png

    For more information, see Configure CORS.

Usage notes

OSS SDK for Browser.js uses Browserify and Babel to generate and compile code for your browser. However, the following features are not supported in browsers because of the limits of the browser environment:

  • Streaming upload: Chunked encoding cannot be configured in browsers. We recommend that you use multipart upload instead of streaming upload.

  • Local file management: Local file systems cannot be managed in browsers. We recommend that you use signed URLs to download objects.

  • OSS does not support bucket-related requests across origins. We recommend that you perform bucket-related operations in the OSS console.

Download OSS SDK for Browser.js

Demos in the documents on the Alibaba Cloud official site are based on OSS SDK for Browser.js V6.x. If you use earlier versions of OSS SDK for Browser.js, visit GitHub to see the Developer Guide for V5.x. To upgrade OSS SDK for Browser.js to V6.x, see the upgrade documents.

Install OSS SDK for Browser.js

  • OSS SDK for Browser.js supports the following browsers:

    • Internet Explorer V10 or later

    • Edge

    • Major versions of Google Chrome, Firefox, and Safari

    • Default browsers of Android, iOS, and Windows Phone of major versions

  • Installation methods

    You can install OSS SDK for Browser.js by using one of the following methods:

    Use a browser to import OSS SDK for Browser.js

    Important

    Some browsers do not provide native support for promises. In this case, you must import a promise library. For example, you need to import promise-polyfill to Internet Explorer 10 and 11.

    <!-- Import online -->
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.1.min.js"></script>      
    <!-- Import locally -->
    <script src="./aliyun-oss-sdk-6.18.1.min.js"></script>
    Note
    • If you import the SDK online, the speed depends on the stability of Alibaba Cloud CDN servers. We recommend that you import the SDK locally or by using your own implementation.

    • If you import the SDK from a local resource in a sample program, set src to the path of the local resource relative to the path of the sample program.

    • In this example, OSS SDK 6.18.1 is used. For information about more versions, visit GitHub.

    The following code provides an example on how to use an OSS object:

    Important

    In most cases, OSS SDK for Browser.js is used in browsers. To prevent your AccessKey pair from being exposed, we recommend that you use temporary access credentials obtained from STS to access OSS.

    Temporary access credentials consist of an AccessKey pair and a security token. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain temporary access credentials. For more information, see Use temporary credentials provided by STS to access OSS.

    <script type="text/Browser.jsscript">
      const client = new OSS({
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
        region: 'yourRegion',
        // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // Specify the security token obtained from STS. 
        stsToken: 'yourSecurityToken',
        refreshSTSToken: async () => {
        // Obtain temporary access credentials from STS. 
          const info = await fetch('your_sts_server');
          return {
            accessKeyId: info.accessKeyId,
            accessKeySecret: info.accessKeySecret,
            stsToken: info.stsToken
          }
        },
        // Set the time interval of refreshing temporary access credentials. Unit: milliseconds. 
        refreshSTSTokenInterval: 300000,
        // Specify the name of the bucket. 
        bucket: 'examplebucket'
      });
    </script>                           

    Use npm to install the package of OSS SDK for Browser.js

    npm install ali-oss

    After the installation is complete, you can use the import or require syntax to use OSS SDK for Browser.js. Browsers do not provide native support for the require syntax. Therefore, you need to use a packaging tool such as webpack or browserify in the development environment.

    const OSS = require('ali-oss');
    
    const client = new OSS({
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
        region: 'yourRegion',
        // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // Specify the security token obtained from STS. 
        stsToken: 'yourSecurityToken',
        refreshSTSToken: async () => {
        // Obtain temporary access credentials from the STS that you set up. 
          const info = await fetch('your_sts_server');
          return {
            accessKeyId: info.accessKeyId,
            accessKeySecret: info.accessKeySecret,
            stsToken: info.stsToken
          }
        },
        // Set the time interval at which to refresh the temporary access credentials. Unit: milliseconds. 
        refreshSTSTokenInterval: 300000,
        // Specify the name of the bucket. 
        bucket: 'examplebucket'
    });

Usage notes

You can use the synchronous or asynchronous mode when you use OSS SDK for Browser.js. new OSS() is used to create OSS clients when the synchronous or asynchronous mode is used.

Synchronous mode

The async/await method defined in JavaScript ES7 is used to synchronize asynchronous operations.

The following code provides an example on how to upload an object in synchronous mode:

// Create an OSSClient instance. 
const client = new OSS(...);

async function put () {
  try {
    // object specifies the name of the uploaded object. 
    // file specifies the name of the file that you want to upload from the browser. Files of the HTML5 and Blob types are supported. 
    const r1 = await client.put('object', file);
    console.log('put success: %j', r1);
    const r2 = await client.get('object');
    console.log('get success: %j', r2);
  } catch (e) {
    console.error('error: %j', e);
  }
}

put();                    

Asynchronous mode

Asynchronous operations are performed in a way similar to callbacks. An API operation returns a Promise object for a request. The then() method is used to process the returned result, and the catch() method is used to handle errors.

The following code provides an example on how to upload an object in asynchronous mode:

// Create an OSSClient instance. 
const client = new OSS(...);

// object specifies the name of the uploaded object. 
// file specifies the name of the file that you want to upload from the browser. Files of the HTML5 and Blob types are supported. 
client.put('object', file).then(function (r1) {
  console.log('put success: %j', r1);
  return client.get('object');
}).then(function (r2) {
  console.log('get success: %j', r2);
}).catch(function (err) {
  console.error('error: %j', err);
});