全部產品
Search
文件中心

Object Storage Service:初始化(Browser.js SDK)

更新時間:Dec 18, 2025

Client是OSS Browser.js的用戶端,用於管理儲存空間和檔案等OSS資源。使用Browser.js SDK發起OSS請求時,您需要初始化一個Client執行個體,並根據需要修改預設配置項。

前提條件

已安裝Browser.js SDK。具體操作,請參見安裝(Browser.js SDK)

建立Client

V4簽名(推薦)

推薦使用更安全的V4簽名演算法。使用V4簽名初始化時,需要聲明authorizationV4。OSS Browser.js SDK 6.20.0及以上版本支援V4簽名。

以使用OSS網域名稱初始化時使用V4簽名為例,其他通過自訂網域名等初始化的情境可參考以下樣本執行相應修改。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <!--匯入SDK檔案-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.20.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        // yourRegion填寫Bucket所在地區。以華東1(杭州)為例,yourRegion填寫為oss-cn-hangzhou。
        region: 'yourRegion',
	authorizationV4: true,
        // 從STS服務擷取的臨時存取金鑰(AccessKey ID和AccessKey Secret)。
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // 從STS服務擷取的安全性權杖(SecurityToken)。
        stsToken: 'yourSecurityToken',
        // 填寫Bucket名稱,例如examplebucket。
        bucket: "examplebucket",
      });
    </script>
  </body>
</html>

V1簽名(不推薦)

重要

阿里雲Object Storage Service自2025年03月01日起不再對新使用者(即新UID )開放使用V1簽名,並將於2025年09月01日起停止更新與維護且不再對新增Bucket開放使用V1簽名。請儘快切換到V4簽名,避免影響服務。更多資訊,請參見公告連結

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <!--匯入SDK檔案-->
    <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({
        // yourRegion填寫Bucket所在地區。以華東1(杭州)為例,yourRegion填寫為oss-cn-hangzhou。
        region: 'yourRegion',
        // 從STS服務擷取的臨時存取金鑰(AccessKey ID和AccessKey Secret)。
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // 從STS服務擷取的安全性權杖(SecurityToken)。
        stsToken: 'yourSecurityToken',
        // 填寫Bucket名稱,例如examplebucket。
        bucket: "examplebucket",
      });
    </script>
  </body>
</html>

配置Client

您可以在初始化Client時按需添加配置項,例如通過timeout指定請求逾時時間,通過stsToken指定臨時訪問憑證等。關於Browser.js支援的配置項以及配置樣本,具體參數請參考下方說明。

options參數說明:

  • accessKeyId {String}:在阿里雲控制台網站上建立的存取金鑰。

  • accessKeySecret {String}:在阿里雲控制台建立的存取金鑰秘密。

  • [stsToken] {String}:用於臨時授權。

  • [refreshSTSToken] {Function}:當STS資訊到期時自動化佈建stsToken、accessKeyId、accessKeySecret的函數。傳回值必須是包含stsToken、accessKeyId、accessKeySecret的對象。

  • [refreshSTSTokenInterval] {number}:STS令牌重新整理間隔時間(毫秒)。應小於STS資訊的到期間隔,預設為300000毫秒(5分鐘)。

  • [bucket] {String}:您想訪問的預設Bucket。如果沒有Bucket,請先使用putBucket()建立一個。

  • [endpoint] {String}:OSS地區網域名稱。優先順序高於region。根據需要設定為外網網域名稱、內網網域名稱或加速網域名稱等,請參考終端節點列表。

  • [region] {String}:Bucket資料所在的地區位置,預設為oss-cn-hangzhou。

  • [internal] {Boolean}:是否通過阿里雲內網訪問OSS,預設為false。如果您的伺服器也在阿里雲上運行,可以設定為true以節省大量費用。

  • [secure] {Boolean}:指示OSS用戶端使用HTTPS(secure: true)還是HTTP(secure: false)協議。

  • [timeout] {String|Number}:針對所有操作的執行個體層級逾時時間,預設為60秒。

  • [cname] {Boolean}:預設為false,使用自訂網域名訪問OSS。如果為true,則可以在endpoint欄位中填寫自訂網域名。

  • [isRequestPay] {Boolean}:預設為false,表示是否開啟Bucket的要求者支付功能,如果為true,會向OSS伺服器發送頭部'x-oss-request-payer': 'requester'。

  • [useFetch] {Boolean}:預設為false,僅在瀏覽器環境中生效。如果為true,意味著使用fetch模式上傳對象,否則使用XMLHttpRequest。

  • [retryMax] {Number}:當請求因網路錯誤或逾時出錯時自動重試發送請求的最大次數。使用putStream時不支援重試。

  • [authorizationV4] {Boolean}:使用V4簽名。預設為false。

樣本

  • 基本用法

    const OSS = require('ali-oss');
    
    const store = new OSS({
      region: 'yourRegion',
      authorizationV4: true,
      accessKeyId: 'your access key',
      accessKeySecret: 'your access secret',
      stsToken: 'yourSecurityToken',
      bucket: 'your bucket name',
    });
  • 使用加速訪問endpoint

    說明

    Global Acceleration訪問endpoint:oss-accelerate.aliyuncs.com

    中國內地以外地區的加速訪問endpoint:oss-accelerate-overseas.aliyuncs.com

    const OSS = require('ali-oss');
    
    const store = new OSS({
      region: 'yourRegion',
      authorizationV4: true,
      accessKeyId: 'your access key',
      accessKeySecret: 'your access secret',
      stsToken: 'yourSecurityToken',
      bucket: 'your bucket name',
      endpoint: 'oss-accelerate.aliyuncs.com',
    });
  • 使用自訂訪問方式

    const OSS = require('ali-oss');
    
    const store = new OSS({
      region: 'yourRegion',
      authorizationV4: true,
      stsToken: 'yourSecurityToken',
      accessKeyId: 'your access key',
      accessKeySecret: 'your access secret',
      cname: true,
      endpoint: 'your custome domain',
    });
  • 使用STS Token訪問

    const OSS = require('ali-oss');
    
    const store = new OSS({
      region: 'yourRegion',
      authorizationV4: true,
      accessKeyId: 'your STS key',
      accessKeySecret: 'your STS secret',
      stsToken: 'your STS token',
      refreshSTSToken: async () => {
        const info = await fetch('you sts server');
        return {
          accessKeyId: info.accessKeyId,
          accessKeySecret: info.accessKeySecret,
          stsToken: info.stsToken,
        };
      },
      refreshSTSTokenInterval: 300000,
    });
  • 使用流重新嘗試請求

    for (let i = 0; i <= store.options.retryMax; i++) {
      try {
        const result = await store.putStream('<example-object>', fs.createReadStream('<example-path>'));
        console.log(result);
        break; // break if success
      } catch (e) {
        console.log(e);
      }
    }
  • 使用V4簽名,並使用可選的additionalHeaders選項(類型為字串數組),其中的值需要包含在標題中

    const OSS = require('ali-oss');
    
    const store = new OSS({
      accessKeyId: 'your access key',
      accessKeySecret: 'your access secret',
      bucket: 'your bucket name',
      region: 'oss-cn-hangzhou',
      authorizationV4: true ,
      stsToken: 'yourSecurityToken',
    });
    
    try {
      const bucketInfo = await store.getBucketInfo('your bucket name');
      console.log(bucketInfo);
    } catch (e) {
      console.log(e);
    }
    
    try {
      const putObjectResult = await store.put('your bucket name', 'your object name', {
        headers: {
          // The headers of this request
          header1: 'value1',
          header2: 'value2',
        },
        // The keys of the request headers that need to be calculated into the V4 signature. Please ensure that these additional headers are included in the request headers.
        additionalHeaders: ['additional header1', 'additional header2'],
      });
      console.log(putObjectResult);
    } catch (e) {
      console.log(e);
    }