阿里云AliyunSTSAssumeRoleAccess上传大文件至oss

最近需要上传大文件至阿里云的oss

在常规的使用中

是将appid及secret和bucket写在配置文件中,然后安装oss包来使用

因为是大文件,所以没有按照这种方式

现在的方法是前端直接调用阿里云的接口来上传,因为大文件很占带宽流量

现在需要阿里云开通Ram权限

AssumeRole - 获取扮演角色的临时身份凭证

具体方法是前端调用后端的接口来生成临时的token,然后前端直接将大文件切片上传到阿里云,上传成功后阿里云会自动合并文件

代码如下

```
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

//根据阿里云oss的id和secret生成ststoken,需要开通ram权限
public function getStsToken(){
$config = config('upload.aliyun_oss');
$accessKeyId = $config['AccessKeyID'];
$accessKeySecret = $config['AccessKeySecret'];
$endpoint = $config['endpoint'];
$regionId = $config['region'];
$bucket = $config['bucket'];
$role_arn = $config['rolearn'];
AlibabaCloud::accessKeyClient($accessKeyId,$accessKeySecret)
->regionId($regionId)
->asDefaultClient();
try {
$result = AlibabaCloud::rpc()
->product('sts')
->version('2015-04-01')
->scheme('https')
->action('AssumeRole')
->method('POST')
->host('sts.aliyuncs.com')
->options([
'query'=>[
'RegionId'=>$regionId,
//角色中的ARN值
'RoleArn'=>$role_arn,
'RoleSessionName'=>'upload',
'DurationSeconds' => 3600,
]
])
->request();
$res = $result->toArray();
$res['Credentials']['regionId'] = 'oss-'.$regionId;
$res['Credentials']['bucket'] = $bucket;
$res['Credentials']['endpoint'] = $endpoint;
return $this->jsonData($res);
}catch (ClientException $e){
return $this->jsonError($e->getErrorMessage());
}catch (ServerException $e){
return $this->jsonError($e->getErrorMessage());
}
}
```

相关官方文档`https://help.aliyun.com/document_detail/100624.html?spm=a2c4g.11186623.0.0.4e463767X2OTcd`

    A+
发布日期:2023年02月21日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: