This topic describes how to use OSS SDK for Browser.js to perform operations such as uploading and downloading objects and viewing the list of objects.

Prerequisites

A cross-origin resource sharing (CORS) rule is configured for the bucket. For more information, see Configure CORS rules.

The CORS rule meets the following requirements if you want to access OSS by using a browser:
  • Source is set to an asterisk (*).
  • GET, POST, PUT, DELETE and HEAD are selected for Allowed Methods.
  • Allowed Headers is set to *.
  • Exposed Headers is set to ETag, x-oss-request-id, and x-oss-version-id.
cors
Note You can configure multiple CORS rules for the bucket. In this case, you must set the preceding CORS rule as the first rule.

Background information

The AccessKey pair of an Alibaba Cloud account has permissions on all API operations of OSS. We recommend that you use STS to authorize the client. You can use STS to grant a third-party application or your RAM user an access credential that has custom permissions and a custom validity period. For more information, see Access OSS by using a temporary access credential provided by STS.

For more information about how to use browsers, see Browser.

For more information about sample projects, see example.

Use the SDK

Currently, browsers do not support bucket-related operations, such as GetBucket (ListObjects), GetBucketLogging, and GetBucketReferer. However, you can use a browser to perform object-related operations, such as PutObject and GetObject.

Notice The environment of a browser is untrusted. Security risks may arise if you store AccessKey IDs and AccessKey secrets in a browser. We recommend that you use plaintext only for tests and use STS authentication mode or self-signed mode for business application. For more information, see Authorized access and Set up direct data transfer for mobile apps.
  • Import the SDK

    Include the following information in <head> of the HTML file:

    <script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-x.x.x.min.js"></script>
                        

    For more information about the methods to import the SDK, see Installation.

    You can use the new OSS method to create a client. This method provides an asynchronous API operation similar to the callback method to process the returned results in .then() and handle errors in .catch().

  • Build an STS server and obtain temporary authorization information from the client
    1. Use the STS-based signature services exclusive to SDKs or API operations. To help you get started with the STS service, OSS provides SDK demos in the following programming languages:
      Note The preceding demos are for reference only. You must develop code required for authentication and other functions in the production environment.
    2. Initiate requests to the STS service built in the frontend (browser) to obtain the STS temporary authorization information.
      <script type="text/javascript">
        // OSS.urlib is the logic of sending requests encapsulated within the SDK. Developers can use any library that sends requests to send requests to the STS server.
        OSS.urllib.request("http://your_sts_server/", {method: 'GET'}, (err, response) => {
            if (err) {
              return alert(err);
            }
            try {
              result = JSON.parse(response);
            } catch (e) {
                errmsg = 'parse sts response info error: ' + e.message;
                return alert(errmsg);
            }
           // console.log(result)
         })
      </script>
                                  
  • Upload objects

    You can call the multipartUpload operation to upload objects. For more information about multipartUpload, see Multipart upload.

    <body>
      <input type="file" id="file" />
      <script type="text/javascript">
        document.getElementById('file').addEventListener('change', function (e) {
          let file = e.target.files[0];
          let storeAs = 'upload-file';
          console.log(file.name + ' => ' + storeAs);
          // OSS.urlib is the logic of sending requests encapsulated within the SDK. Developers can use any library that sends requests to send requests to the STS server.
          OSS.urllib.request("http://your_sts_server/", {method: 'GET'}, (err, response) => {
              if (err) {
                return alert(err);
              }
              try {
                result = JSON.parse(response);
              } catch (e) {
                return alert('parse sts response info error: ' + e.message);
              }
              let client = new OSS({
                accessKeyId: result.AccessKeyId,
                accessKeySecret: result.AccessKeySecret,
                stsToken: result.SecurityToken,
                // region indicates the region from which OSS services are provided. Example: oss-cn-hangzhou.
                region: '<Your region>',
                bucket: '<Your bucket name>'
              });
              // You can set storeAs to an object name such as file.txt or a directory such as abc/test/file.txt to upload the object to the root folder or the specified folder in the bucket.
              // You can set file to file objects, Blob data, or OSS buffers.
              client.multipartUpload(storeAs, file).then(function (result) {
                console.log(result);
              }).catch(function (err) {
                console.log(err);
              });
            });
        });
      </script>
    </body>
                        
  • Download objects

    OSS generates a signed URL as the download link of an object. You need only to click the link to download the object.

    <body>
      <input type="button" id="download" value="Download" />
      <script type="text/javascript">
        document.getElementById('download').addEventListener('click', function (e) {
          let objectKey = 'test/download_file';
          let saveAs = 'download_file';
          console.log(objectKey + ' => ' + saveAs);
          // OSS.urlib is the logic of sending requests encapsulated within the SDK. Developers can use any library that sends requests to send requests to the STS server.
          OSS.urllib.request("http://your_sts_server/", {method: 'GET'}, (err, response) => {
              if (err) {
                return alert(err);
              }
              try {
                result = JSON.parse(response);
              } catch (e) {
                return alert('parse sts response info error: ' + e.message);
              }
              let client = new OSS({
                accessKeyId: result.AccessKeyId,
                accessKeySecret: result.AccessKeySecret,
                stsToken: result.SecurityToken,
                // region indicates the region from which OSS services are provided. Example: oss-cn-hangzhou.
                region: '<Your region>',
                bucket: '<Your bucket name>'
              });
              let result = client.signatureUrl(objectKey, {
                expires: 3600,
                response: {
                  'content-disposition': 'attachment; filename="' + saveAs + '"'
                }
              });
              console.log(result);
              window.location = result;
            });
        });
      </script>
    </body>
                        
  • View objects in a bucket

    The following code provides an example on how to view objects in a bucket:

    <script type="text/javascript">
    OSS.urllib.request("http://your_sts_server/", {method: 'GET'}, (err, response) => {    
      if (err) {
        return alert(err);
      }
    
      try {
        result = JSON.parse(response);
      } catch (e) {
        return alert('parse sts response info error: ' + e.message);
      }
    
      let client = new OSS({
        accessKeyId: result.AccessKeyId,
        accessKeySecret: result.AccessKeySecret,
        stsToken: result.SecurityToken, 
        // region indicates the region from which OSS services are provided. Example: oss-cn-hangzhou.
        region: '<Your region>',
        bucket: '<Your bucket name>'
      });
    
      client.list({
        'max-keys': 10
      }).then(function (result) {
        console.log(result);
      }).catch(function (err) {
        console.log(err);
      });
    });
    </script>
                        

    You can open the HTML file in Google Chrome and view the listed objects in Chrome DevTools.