SDK使用方法
首先需要在天翼云官网下载小程序SDK,下载地址为:oss-miniprogram-sdk.zip。下载完成后可以直接解压SDK压缩包到程序目录中使用。Demo地址为oss-miniprogram-demo。
引入SDK
const osssdk = require('./oss-miniprogram-sdk/oss');
在package.json文件中添加依赖
"dependencies": {
"oss-miniprogram-sdk": "^1.0.1"
}
引入SDK
const osssdk = require('oss-miniprogram-sdk');
使用SDK功能前,需要创建Client,示例代码如下:
let accessKey = "<your-access-key>";
let secretAccessKey = "<your-secret-key>";
let sessionToken = "<your-session-token>";
let endpoint = "<your-endpoint>"; // e.g. https://xxx.xstore.ctyun.cn
this.bucket = "<your-bucket-name>";
this.credentials = {
AccessKeyId: accessKey,
SecretAccessKey: secretAccessKey,
SessionToken: sessionToken,
}
var config = {
Creds: this.credentials,
EndPoint: endpoint,
}
this.ossClient = new osssdk.OSS(config);
后续的接口调用都会基于该client来进行。
使用assumeRole请求申请临时凭证,使用服务端返回的accessKeyId,secretAccessKey和sessionToken来初始化s3对象。使用过程中,需要更新凭证,保证凭证不过期。使用过期凭证的请求,服务端会返回403(AccessDenied)。
updateCredentials: function(ak, sk, token) {
this.credentials.AccessKeyId = ak;
this.credentials.SecretAccessKey = sk;
this.credentials.SessionToken = token;
},
listObjects: function() {
var req = {
Bucket: this.bucket,
}
this.ossClient.ListObjects(req, function(err, res){
if(err != null){
console.log(err)
return
}
console.log(res)
});
},
getObject: function() {
var req = {
Bucket: this.bucket,
Key: "ExampleObject.txt"
}
this.ossClient.GetObject(req, function(err, res){
if(err != null){
console.log(err)
return
}
var dec = new TextDecoder("utf-8")
console.log(dec.decode(res.buffer))
});
},
upload: function () {
wx.chooseMessageFile({
success: (res) => {
const tempFilePaths = res.tempFiles
var req = {
Bucket: this.bucket,
Key: "ExampleObject1.jpg",
FilePath: tempFilePaths[0].path,
PartSize: 5*1024*1024,
}
var manager = new osssdk.UploadManager(this.ossClient);
manager.UploadFile(req, function(err, res){
if(err != null){
console.log(err)
return
}
console.log(res)
});
}
})
}
参数:
参数名 | 类型 | 说明 |
---|---|---|
Bucket | String | 桶名称 |
Key | String | 对象名称 |
FilePath | String | 要上传的文件路径 |
PartSize | int | 上传分片大小 |
Acl | String | 文件访问权限,如private,public-read,默认是private |
ContentType | String | 文件的Content-type,如image/jpeg,默认是application/octet-stream |