瀏覽器支援
- IE(>=10)和Edge
- 主流版本的Chrome/Firefox/Safari
- 主流版本的Android/iOS/WindowsPhone
注意:
在IE中使用需要在引入SDK之前引入promise庫:
瀏覽器低版本支援
SDK是通過File API進行檔案操作,在一些較低版本的瀏覽器運行會出現問題。可以利用一些第三方的上傳外掛程式,通過對OSS API的實現,實現OSS的上傳、下載等操作。具體範例請參見Web端直傳實踐。
設定
Bucket設定
從瀏覽器中直接存取OSS,需要對Bucket的CORS屬性進行設定,設定方式如下所示:
- 將 來源 設定成
*
- 將 Method 設定成
GET, POST, PUT, DELETE, HEAD
- 將 Allowed Header 設定成
*
- 將 Expose Header 設定成
etag
注意:請將該條CORS規則設定成所有CORS規則的第一條。
STS設定
為了不在網頁中暴露AccessKeyId和AccessKeySecret,我們採用STS進行臨時授權。授權伺服器由使用者維護,只有認證的使用者才能向授權伺服器申請臨時許可權。設定子帳號和STS的Policy,參考Node.js STS AppServer搭建自己的授權伺服器。
例子
下面我們將使用SDK開發一個網頁應用,包含4個功能:
- 上傳檔案
- 上傳文本
- 列出檔案
- 下載檔案
完整的代碼可以在oss-in-browser找到。最終的效果如下:
下面的介紹將以“上傳檔案”為例:
1. 建立網頁
對於“上傳檔案”的功能,在網頁上需要4個控制項:
- 一個檔案選擇框,用於選擇需要上傳的檔案
- 一個文字框,用於輸入上傳到OSS的Object名字
- 一個按鈕,用於開始上傳
- 一個進度條,用於顯示上傳的進度
下面的代碼建立了這4個控制項,其中class="xxx"
是為了使用Bootstrap樣式,可以先忽略。
<div class="form-group">
<label>Select file</label>
<input type="file" id="file" />
</div>
<div class="form-group">
<label>Store as</label>
<input type="text" class="form-control" id="object-key-file" value="object" />
</div>
<div class="form-group">
<input type="button" class="btn btn-primary" id="file-button" value="Upload" />
</div>
<div class="form-group">
<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>
2. 添加樣式
接下來為網頁添加一些樣式,讓它更好看一些,這裡我們用到了Bootstrap。在網頁的<head>
標籤中加入樣式:
<head>
<title>OSS in Browser</title>
<link rel="stylesheet" href="bootstrap.min.css" />
</head>
其中bootstrap.min.css
可以在bootstrap的官網下載。
3. 添加指令碼或直譯式程式
到目前為止,網頁是靜態,點擊上面的按鈕也不會有反應。接下來的重點是為它添加一些JavaScript指令碼或直譯式程式,讓它能夠上傳檔案/下載檔案/列出檔案。
首先在<head>
標籤中引入SDK的開發包:
<head>
<title>OSS in Browser</title>
<link rel="stylesheet" href="bootstrap.min.css" />
<script type="text/javascript" src="http://gosspublic.alicdn.com/aliyun-oss-sdk-x.x.x.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
其中app.js
是真正執行上傳檔案的代碼,內容如下:
const appServer = 'http://localhost:3000';
const bucket = 'js-sdk-bucket-sts';
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);
const client = new OSS({
region: region,
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}`);
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);
}
};
上傳一個檔案分為以下步驟:
- 向授權伺服器申請臨時許可權。其中授權伺服器是網站開發人員構建的用於向終端使用者提供臨時授權的服務。開發人員可以在授權時為不同的使用者提供不同的許可權(參考OSS使用STS)。授權伺服器可以參考這個例子,為了簡便,例子中授權伺服器直接向使用者返回臨時憑證。
- 使用臨時密鑰建立OSS Client。
- 通過
multipartUpload
上傳選中的檔案,並通過progress
參數設定進度條。
4. 其他功能
上傳常值內容、獲取檔案清單、下載檔案等功能請參考程式碼範例:OSS in Browser。