This topic describes how to install Object Storage Service (OSS) SDK for Browser.js.

Preparations

  • A Resource Access Management (RAM) user or a Security Token Service (STS) credential is created 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 an STS credential to call API operations or perform routine O&M. If you deploy your service on the client, use an STS credential to call API operations. For more information, see Overview.

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

    For more information, see Configure CORS rules.

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

    • Sources: Specify an accurate domain name, such as www.aliyun.com or a domain name that contains an asterisk (*) as the wildcard, such as *.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.
    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 documents on the official website are based on OSS SDK V6.X.For more information about versions earlier than 6.X, visit oss-nodejs-sdk. To upgrade your SDK version to 6.X, see What is OSS?.

Install OSS SDK for Browser.js

  • OSS SDK for Browser.js supports the following browsers:
    • Internet Explorer 10 and later versions and Microsoft 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
      Notice Some browsers do not provide native support for promise. In this case, you must import a promise library. For example, you must import the promise-polyfill library for Internet Explorer 10 and 11.
      <!-- Import online resources -->
      <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-x.x.x.min.js"></script>                           
      <!-- Import local resources -->
      <script src="./aliyun-oss-sdk-x.x.x.min.js"></script>                           
      Note
      • If you import online resources, the speed depends on the stability of Alibaba Cloud Content Delivery Network (CDN) servers. We recommend that you import the SDK from local resources or build the SDK by yourself.
      • If you import the SDK from local resources in a sample program, set src to the path of the local resources relative to the path of the sample program.
      • The aliyun-oss-sdk-x.x.x.min.js part in src indicates the name of the local resource, in which x.x.x indicates the version number of the SDK. For more information about the versions, visit oss-js-sdk.
      The following code provides an example on how to use an OSS object:
      Note For more information about how to configure STS, see Use a temporary credential provided by STS to access OSS in OSS Developer Guide. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain a temporary access credential. The temporary access credential contains a security token and a temporary AccessKey pair that consists of an AccessKey ID and an AccessKey secret. The minimum validity period of a temporary access credential is 900 seconds. The maximum validity period of a temporary access credential is the maximum session duration specified by the current role. For more information, see Specify the maximum session duration for a RAM role.
      <script type="text/javascript">
        const client = new OSS({
          // Set yourRegion to the endpoint of the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou. 
          region: 'yourRegion',
          // Obtain a temporary AccessKey pair from STS. 
          accessKeyId: 'yourAccessKeyId',
          accessKeySecret: 'yourAccessKeySecret',
          // Obtain a security token from STS. 
          stsToken: 'yourSecurityToken',
          refreshSTSToken: async () => {
          // Obtain a temporary access credential 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 credential. Unit: milliseconds. 
          refreshSTSTokenInterval: 300000,
          // Specify the bucket name. 
          bucket: 'examplebucket'
        });
      </script>                           
    • Use npm to install the package of OSS SDK for Browser.js
      npm install ali-oss                           

      After the package is installed, 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 must use a packaging tool such as webpack or browserify in the development environment.

      const OSS = require('ali-oss');
      
      const client = new OSS({
          // Set yourRegion to the endpoint of the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou. 
          region: 'yourRegion',
          // Obtain a temporary AccessKey pair from STS, which consists of an AccessKey ID and an AccessKey secret. 
          accessKeyId: 'yourAccessKeyId',
          accessKeySecret: 'yourAccessKeySecret',
          // Obtain a security token from STS. 
          stsToken: 'yourSecurityToken',
          refreshSTSToken: async () => {
          // Obtain a temporary access credential 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 credential. Unit: milliseconds. 
          refreshSTSTokenInterval: 300000,
          // Specify the bucket name. 
          bucket: 'examplebucket'
      });

Implementation methods

You can use the synchronous or asynchronous mode when you use OSS SDK for Browser.js.

  • Synchronous mode: The async/await method defined in JavaScript ES7 is used to synchronize asynchronous operations.
  • Asynchronous mode: Asynchronous operations are performed in a way similar to callback. 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.
Note new OSS() is used to create OSS clients when the synchronous or asynchronous mode is used.

The following code provides examples on how to upload and download an object in synchronous and asynchronous modes:

  • 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
    // Create an OSSClient. 
    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);
    });