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

Cross-origin resource sharing (CORS) rules are set. For more information, see Configure CORS rules.

The CORS rules meet the following requirements if you need to access OSS by using a browser:
  • Source: Enter *.
  • Allowed Methods: Select GET, POST, PUT, DELETE and HEAD.
  • Allowed Headers: Enter *.
  • Exposed Headers: Enter ETag and x-oss-request-id.
cors
Note You can configure multiple CORS rules. Set the preceding CORS rule as the first option.

Background information

The AccessKey pair of an Alibaba Cloud account has permissions on all API operations in 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 with a customized validity period and permissions. For more information, see Access OSS with 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, but support 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 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 process 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 APIs. To help you get started with the STS service, OSS provides SDK demos in multiple 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 refers to the region ID of the OSS service you apply for, such as oss-cn-hangzhou.
                region: '<Your region>',
                bucket: '<Your bucket name>'
              });
              // 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 current bucket or the specified folder in the bucket.
              // Set file to file objects, Blob data, and OSS buffers.
              client.multipartUpload(storeAs, file).then(function (result) {
                console.log(result);
              }).catch(function (err) {
                console.log(err);
              });
            });
        });
      </script>
    </body>
    					
  • Download objects

    Use a signed URL to generate 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 refers to the region ID of the OSS service you apply for, such as 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 refers to the region ID of the OSS service you apply for, such as 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>
    					

    Open the HTML file in Google Chrome. Open Developer tools of the browser. You can view the listed objects.