All Products
Search
Document Center

Object Storage Service:Getting started with OSS SDK for Browser.js

Last Updated:Sep 25, 2023

This topic describes how to use OSS SDK for Browser.js to perform operations such as uploading, downloading, and querying objects.

Prerequisites

  • OSS SDK for Browser.js is installed. For more information, see Installation.

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

Usage notes

  • OSS SDK for Browser.js does not support bucket-related operations in a browser. OSS SDK for Browser.js supports only object-related operations, such as PutObject and GetObject.

  • 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 Security Token Service (STS) to access OSS.

    The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For more information about how to obtain temporary access credentials, see Use STS for temporary access authorization.

Common operations

This section describes common operations by using OSS SDK for Browser.js.

Build an STS server and obtain temporary authorization information from a client

  1. Build an STS server.

    To help you build an STS server, OSS provides OSS SDKs in the following languages:

    Important

    The preceding demos are for reference only. You must develop required code for authentication and other features in the production environment.

  2. Initiate requests to the STS server from a browser to obtain the STS temporary authorization information.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>Document</title>
      </head>
      <body>
        <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
        <script type="text/javascript">
          // OSS.urlib is the logic for sending requests encapsulated within OSS SDKs. Developers can use a library that sends requests to send requests to the STS server. 
          // Set your_sts_server to the IP address or domain name of the STS server that you built in Step 1. 
          OSS.urllib.request(
            "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>
      </body>
    </html>
                                

Upload objects

The following sample code provides an example on how to call the multipartUpload operation to upload objects:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <button id="submit">Upload</button>
    <input id="file" type="file" />
    <!-- Import the SDK file -->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      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 Security Token Service (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",
        // Specify the name of the bucket. Example: examplebucket. 
        bucket: "examplebucket",
      });

      const headers = {
        // Specify the caching behavior of the web page when the object is downloaded. 
        "Cache-Control": "no-cache",
        // Specify the name of the object when the object is downloaded. 
        "Content-Disposition": "example.txt",
        // Specify the content encoding format of the object when the object is downloaded. 
        "Content-Encoding": "utf-8",
        // Specify the validity period of the request. Unit: milliseconds. 
        Expires: "1000",
        // Specify the storage class of the object. 
        "x-oss-storage-class": "Standard",
        // Specify the tag for the object. You can specify multiple tags for the object at the same time. 
        "x-oss-tagging": "Tag1=1&Tag2=2",
        // Specify whether existing objects are overwritten by objects with the same names when the multipart upload task is initiated. In this example, this parameter is set to true, which indicates that existing objects cannot be overwritten by objects that have the same names. 
        "x-oss-forbid-overwrite": "true",
      };

      // Specify the name of the object that is uploaded to the examplebucket bucket. Example: exampleobject.txt. 
      const name = "exampleobject.txt";
      // Query DOM. 
      const submit = document.getElementById("submit");
      const options = {
        // Query the progress, the checkpoint, and the return value of the multipart upload task. 
        progress: (p, cpt, res) => {
          console.log(p);
        },
        // Specify the number of parts that can be uploaded in parallel. 
        parallel: 4,
        // Specify the size of each part. Default value: 1 MB. Minimum value: 100 KB. 
        partSize: 1024 * 1024,
        // headers,
        // Specify the user metadata of the object. You can call the HeadObject operation to query the object metadata. 
        meta: { year: 2020, people: "test" },
        mime: "text/plain",
      };

      // Configure an event listener. 
      submit.addEventListener("click", async () => {
        try {
          const data = document.getElementById("file").files[0];
          // Start the multipart upload task. 
          const res = await client.multipartUpload(name, data, {
            ...options,
            // Configure an upload callback. 
            // If no callback server is required, delete the callback configurations. 
            callback: {
              // Specify the address of the server that receives the callback request. 
              url: "http://examplebucket.aliyuncs.com:23450",
              // Specify the Host header in the callback request. 
              host: "yourHost",
              /* eslint no-template-curly-in-string: [0] */
              // Specify the body field included in the callback request. 
              body: "bucket=${bucket}&object=${object}&var1=${x:var1}",
              // Specify the Content-Type field in the callback request. 
              contentType: "application/x-www-form-urlencoded",
              customValue: {
                // Specify custom parameters for the callback request. 
                var1: "value1",
                var2: "value2",
              },
            },
          });
          console.log(res);
        } catch (err) {
          console.log(err);
        }
      });
    </script>
  </body>
</html>

Download objects

OSS generates a signed URL as the download link of an object. You can use the link to download the object.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <!-- Import the SDK file -->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      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",
        // Specify the name of the bucket. 
        bucket: "examplebucket",
      });

      // Set the response header to automatically download an object by using the URL, and set the name of the local file after the object is downloaded. 
      const filename = "examplefile.txt";
      const response = {
        "content-disposition": `attachment; filename=${encodeURIComponent(
          filename
        )}`,
      };
      // Specify the full path of the object. Do not include the bucket name in the full path. 
      const url = client.signatureUrl("exampleobject.txt", { response });
      console.log(url);
    </script>
  </body>
</html>

List objects

The following sample code provides an example on how to list objects:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
  </head>
  <body>
    <script>      
      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 that you obtained from STS. 
        stsToken: 'yourSecurityToken',
        // Specify the name of the bucket. Example: examplebucket. 
        bucket: "examplebucket",
      });

      async function list(dir) {
        try {
          // By default, up to 1,000 objects are listed. 
          let result = await client.list();
          console.log(result);

          // The list operation continues from the last object that was stopped in the previous list operation. 
          if (result.isTruncated) {
            let result = await client.list({ marker: result.nextMarker });
          }

          // List the objects whose names start with the prefix 'ex'. 
          result = await client.list({
            prefix: "ex",
          });
          console.log(result);

          // List all objects whose names start with the prefix 'ex' and are alphabetically after the 'example' object. 
          result = await client.list({
            prefix: "ex",
            marker: "example",
          });
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      }

      list();
    </script>
  </body>
</html>