[PHP] 腾讯云COS对象存储文件下载

59 阅读1分钟

composer.json

"qcloud/cos-sdk-v5": ">=2.0",
"qcloud_sts/qcloud-sts-sdk": "3.0.*"
public function tencent()
{
    $secretId = "";
    $secretKey = "";
    $bucket = ""; //存储桶名称 格式:BucketName-APPID
    $region = 'ap-guangzhou';

    $sts = new Sts();
    $config = array(
        'url' => 'https://sts.tencentcloudapi.com/', // url和domain保持一致
        'proxy' => '',
        'secretId' => $secretId, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中
        'secretKey' => $secretKey, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中
        'bucket' => $bucket, // 换成你的 bucket
        'region' => $region, // 换成 bucket 所在园区
        'durationSeconds' => 7200, // 密钥有效期
        // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allowPrefix' => array('*'),
        // 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allowActions' => array (
            "name/cos:GetBucket",
            // 简单上传
            'name/cos:PutObject',
            'name/cos:PostObject',
            "name/cos:GetObject",
                    // 简单上传
            'name/cos:PutObject',
            'name/cos:PostObject',
            // 分片上传
            'name/cos:InitiateMultipartUpload',
            'name/cos:ListMultipartUploads',
            'name/cos:ListParts',
            'name/cos:UploadPart',
            'name/cos:CompleteMultipartUpload'
        ),
        // 临时密钥生效条件,关于condition的详细设置规则和COS支持的condition类型可以参考 https://cloud.tencent.com/document/product/436/71306
        "condition" => array(
            "ip_equal" => array(
                "qcs:ip" => array(
                    "你的IP1/24",
                    "IP2/24",
                )
            )
        )
    );

    // 获取临时密钥,计算签名
    // 临时秘钥之后还要去计算签名, 然后再用什么回调方法, 不能直接当成永久秘钥使用
    $tempKeys = $sts->getTempKeys($config);
    echo json_encode($tempKeys);

    $tmpSecretId = $tempKeys['credentials']['tmpSecretId'];
    $tmpSecretKey = $tempKeys['credentials']['tmpSecretKey'];
    $sessionToken = $tempKeys['credentials']['sessionToken'];

    $cosClient = new \Qcloud\Cos\Client(
        array(
            'region' => $region,
            'schema' => 'https', //协议头部,默认为http
            'credentials'=> array(
                'secretId'  => $tmpSecretId,
                'secretKey' => $tmpSecretKey,
                'token'     => $sessionToken)));

    // 获取文件列表
    try {
        $result = $cosClient->listObjects(array(
            'Bucket' => $bucket
        ));
        // 请求成功
        if (isset($result['Contents'])) {
            foreach ($result['Contents'] as $rt) {
                dump($rt);
            }
        }
    } catch (\Exception $e) {
        // 请求失败
        echo($e);
    }

    $signedUrl = $cosClient->getObjectUrl($bucket, "上面那个文件列表里的key", '+10 minutes');
    dd($signedUrl);

}