天天看點

OSS brower js SDK

作者:張醫博

淺談

今天帶來的是 OSS brower js SDK 的安裝過程和使用的 demo 測試用例。

環境準備

OSS brower js SDK 是基于 node js 架構上的服務端程式,服務端啟動以後,提供用戶端的通路位址。

  • 準備 node js 安裝,最好在 9.x.x 以上版本,我目前的測試版本是 v10.9.0
  • 測試浏覽器環境 ( IE>=10,主流版本的 Chrome/Firefox/Safari,主流版本的 Android/iOS/WindowsPhone )

開始安裝

下載下傳源碼 git 庫

npm 開始安裝

  • cd ali-oss ,執行 npm install
  • cd example ,執行 npm install

tips :因為部分浏覽器不支援 promise,需要引入 promise 相容庫。 例如:IE10 和 IE11 需要引入 promise-polyfill 。

修改配置檔案

  1. OSS brower 自帶內建了 STS 生成的功能,其實就是在本地啟動了一個小型的 web server ,這樣用可以通過 STS 的安全方式上傳、下載下傳 OSS。如果要用這個內建的 STS 生成方式,需要修改:
#vim ali-oss/example/server/config.js
module.exports = {
  AccessKeyId: "子賬号 accesskey",
  AccessKeySecret: "子賬号 accesskeysecret",
  RoleArn: "角色 Arn",
  // 建議 Token 失效時間為 1 小時
  TokenExpireTime: '3600',
  PolicyFile: 'policy/all_policy.txt'
};           
  1. 如果使用者不想用這個內建的 STS 生成器,可以自己單獨寫個生成 STS 代碼。那麼上面的 1 步忽略,直接執行以下操作。 vim ali-oss/example/server/config.js,将 bucket 和 region 替換成自己的資訊。
    OSS brower js SDK
  2. 如果使用者自己單獨寫了一個 sts 的程式,需要将 main,js 中依賴的 sts 位址換成自己的通路連結;
    OSS brower js SDK
  3. 在 OSS 上配置跨域頭,避免跨域通路到 OSS 是出現 deny 403 的情況。如果用戶端通路是 http://192.168.1.102/brower/testindex.html ,在 OSS 跨域來源上 IP 也要加入,最友善的做法是配置為 *;
    OSS brower js SDK

啟動

cd ali-oss/example 執行 npm run start

如果使用者想要用 https 的方式上傳,在 OSSClient 初始化時加上 secure:true 就是 https 傳輸了。

const client = new OSS({
        region,
        accessKeyId: creds.AccessKeyId,
        accessKeySecret: creds.AccessKeySecret,
        stsToken: creds.SecurityToken,
        bucket,
        secure:true
      });
           

下圖就是啟動後的效果

OSS brower js SDK

使用遇到問題

上傳回調如何添加

const uploadFile = function uploadFile(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}`);
  const options = {
      progress,
      partSize: 500 * 1024,
          timeout:60000,
      meta: {
          year: 2017,
          people: 'test',
      },
callback: {

//這裡是添加上傳回調的位置
  url: 'https://uploadtest.xueersi.com/v2/sync',
  /* host: 'oss-cn-shenzhen.aliyuncs.com', */
  /* eslint no-template-curly-in-string: [0] */
  body: 'bucket=${bucket}&object=${object}&var1=${x:var1}',
  contentType: 'application/x-www-form-urlencoded',
  customValue: {
    var1: 'value1',
    var2: 'value2',
  },
},
           

如何使用 https 傳輸

const client = new OSS({
        region,
        accessKeyId: creds.AccessKeyId,
        accessKeySecret: creds.AccessKeySecret,
        stsToken: creds.SecurityToken,
        bucket,
        secret: true
      })           

繼續閱讀