All Products
Search
Document Center

Object Storage Service:Application in browsers

Last Updated:Nov 18, 2024

This topic describes the application of OSS SDK for Browser.js in browsers.

Prerequisites

Supported browsers

OSS SDK for Browser.js supports the following browsers:

  • Internet Explorer 10 and later and Microsoft Edge

    Important
    • To use OSS SDK for Browser.js in Internet Explorer, you must import the promise library.

    • OSS SDK for Browser.js uses the File API to perform operations on objects. Therefore, problems may occur when you use the SDK in browsers of earlier versions. We recommend that you use third-party plug-ins to call OSS API operations to perform operations on objects, such as uploading and downloading objects. For more information, see Add signatures on the client and upload data to OSS.

  • Google Chrome, Firefox, or Safari of mainstream versions

  • Default browsers of mainstream versions that are used by Android, iOS, or Windows Phone

Upload an object by using a browser

The following sample code provides an example on how to upload an object by using a browser. Bootstrap is used in the sample code.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://cdn.bootcss.com/twitter-bootstrap/2.3.2/css/bootstrap.min.css"
    />
    <style>
      .form-group {
        margin: 10px;
      }
    </style>
  </head>

  <body style="padding: 100px">
    <div class="form-group">
      <! -- // Create a selection box to select the object that you want to upload to OSS.  -->
      <label>Select file</label>
      <input type="file" id="file" />
    </div>
    <div class="form-group">
      <! -- // Create a text box to specify the name of the object that you want to upload to OSS.  -->
      <label>Store as</label>
      <input type="text" class="form-control" id="object-key-file" value="" />
    </div>
    <div class="form-group">
      <! -- // Create a button to upload the object to OSS.  -->
      <input
        type="button"
        class="btn btn-primary"
        id="file-button"
        value="Upload"
      />
    </div>
    <div class="form-group">
      <! -- // Create a progress bar that displays the upload progress.  -->
      <div class="progress">
        <div
          id="progress-bar"
          class="progress-bar"
          role="progressbar"
          aria-valuenow="0"
          aria-valuemin="0"
          aria-valuemax="100"
          style="min-width: 2em"
        >
          0%
        </div>
      </div>
    </div>
    <!-- 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">
      // Specify the address of your authorization server. Example: http://127.0.0.1:8000/sts. 
      const appServer = "yourStsServer";
      // Specify the name of the bucket. Example: examplebucket. 
      const bucket = "examplebucket";
      // 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. 
      const region = "oss-cn-hangzhou";

      const urllib = OSS.urllib;

      const applyTokenDo = function (func) {
        const url = appServer;
        return urllib
          .request(url, {
            method: "GET",
          })
          .then(function (result) {
            const creds = JSON.parse(result.data);
            // Use temporary access credentials to create an OSSClient instance. 
            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: region,
              authorizationV4: true,
              accessKeyId: creds.AccessKeyId,
              accessKeySecret: creds.AccessKeySecret,
              stsToken: creds.SecurityToken,
              bucket: bucket,
            });

            return func(client);
          });
      };

      let currentCheckpoint;
      const progress = async function progress(p, checkpoint) {
        currentCheckpoint = checkpoint;
        const bar = document.getElementById("progress-bar");
        bar.style.width = `${Math.floor(p * 100)}%`;
        bar.innerHTML = `${Math.floor(p * 100)}%`;
      };

      let uploadFileClient;
      const uploadFile = function (client) {
        if (!uploadFileClient || Object.keys(uploadFileClient).length === 0) {
          uploadFileClient = client;
        }

        const file = document.getElementById("file").files[0];
        const key =
          document.getElementById("object-key-file").value.trim() || "object";
        console.log(`${file.name} => ${key}`);
        // Use multipartUpload to upload the selected objects and use progress to configure the progress bar. 
        const options = {
          progress,
          partSize: 100 * 1024,
          meta: {
            year: 2017,
            people: "test",
          },
        };

        return client
          .multipartUpload(key, file, options)
          .then((res) => {
            console.log("upload success: %j", res);
            currentCheckpoint = null;
            uploadFileClient = null;
          })
          .catch((err) => {
            if (uploadFileClient && uploadFileClient.isCancel()) {
              console.log("stop-upload!");
            } else {
              console.error(err);
            }
          });
      };

      window.onload = function () {
        document.getElementById("file-button").onclick = function () {
          applyTokenDo(uploadFile);
        };
      };
    </script>
  </body>
</html>

References

For the complete sample code for the application in browsers, visit GitHub.