利用STS临时授权实现百度云对象存储前端大文件上传
利用STS临时授权实现百度云对象存储前端大文件上传
工具
百度云 JavaScript SDK
百度云 Python SDK
服务端
环境准备
-
安装pycrypto依赖
安装SDK之前,需要先执行命令
pip install pycrypto
安装pycrypto依赖。
如果安装失败,请执行pip install pycryptodome
-
安装SDK
pip install bce-python-sdk
获取STS临时授权DEMO
授权规则详见官方文档:https://cloud.baidu.com/doc/BOS/s/Tjwvysda9#临时授权访问
# coding: utf-8
import uuid
from baidubce.bce_client_configuration import BceClientConfiguration
from baidubce.auth.bce_credentials import BceCredentials
from baidubce import protocol
from baidubce.services.sts.sts_client import StsClient
access_key = '******'
secret_key = '******'
endpoint = 'sts.bj.baidubce.com'
def get_session_token(bucket_name, mode=None, expire=300):
"""
:param bucket_name: 桶名
:param mode: [READ/WRITE/LIST/GetObject]
:param expire: 过期时间
:return:
"""
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
sts_config = BceClientConfiguration(
credentials=BceCredentials(
access_key_id=access_key,
secret_access_key=secret_key
),
endpoint=endpoint,
protocol=getattr(protocol, 'HTTPS')
)
body = {
"accessControlList": [
{
"service": "bce:bos",
"region": "bj",
"effect": "Allow",
"resource": [f"{bucket_name}/*"],
"permission": mode or ['READ']
}
]
}
sts = StsClient(sts_config)
resp = sts.get_session_token(body, expire)
data = {
'ak': resp.access_key_id,
'sk': resp.secret_access_key,
'expire': resp.expiration,
'session_token': resp.session_token,
'bucket_name': bucket_name,
'endpoint': endpoint,
'key': uuid.uuid4.hex
}
return data
if __name__ == '__main__':
res = get_session_token('bucket-name',mode=['WRITE'], expire=86400)
print(res['ak'])
print(res['sk'])
print(res['session_token'])
# res各项 为前端往百度云bos上传时需要的参数
浏览器
环境准备
Node.js环境:
npm install @baiducloud/sdk
Node.js实现详见官方文档:https://cloud.baidu.com/doc/BOS/s/Djwvyrhiw
这里示例CDN引入的demo
CDN引入方式DEMO
bce-bos-uploader详细使用规则:https://github.com/baidubce/bce-bos-uploader/
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>bce-bos-uploader simple demo</title>
<!--[if lt IE 8]><script src="http://websdk.cdn.bcebos.com/bos/json3/lib/json3.min.js"></script><![endif]-->
<!--[if lt IE 9]><script src="http://websdk.cdn.bcebos.com/bos/js-polyfills/es5.js"></script><![endif]-->
<!--[if lt IE 10]><script src="http://websdk.cdn.bcebos.com/bos/moxie/bin/js/moxie.js"></script><![endif]-->
<script src="https://cdn.bdstatic.com/bce-bos-uploader-lite/1.0.9/bce-bos-uploader-lite.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="file" id="file" >
<button onclick="submit">上传</button>
<script>
function getSTSToken(filename){
# html通过js调用后端接口拿到STS临时授权所需的ak、sk、uptoken、bucket_name、endpoint、key等数据
var resp = null;
$.ajax(
{
type: "GET",
url: 'http://127.0.0.1:8080/sts/Token',
dataType: 'json',
data: {
filename: filename
},
async: false
}
).done(function (data) {
resp = data
});
return resp
}
var uploader = new baidubce.bos.Uploader({
browse_button: '#file',
max_file_size: '3000M',
bos_multipart_min_size: '0',
auto_start: true,
init: {
Key: function (_, file) { // 供使用者自定义key(上传到桶里的名字),可以在这里调用服务端拿到所需参数
data = getSTSToken(file.name)
console.log(data.data)
uploader.setOptions({
bos_ak: data.data.ak,
bos_sk: data.data.sk,
uptoken: data.data.uptoken,
bos_endpoint: data.data.endpoint,
bos_bucket: data.data.bucket_name,
})
return data.data.key
},
FileUploaded: function (_, file, info) {
// 文件上传成功之后,调用这个函数
console.log(info.body);
// 处理成功的业务逻辑
},
Error: function (_, error, file) {
// 如果上传的过程中出错了,调用这个函数
},
}
})
function submit(){
uploader.start()
}
</script>
</body>
</html>
程序猿,要对自己狠一点!