一、开通腾讯云对象存储服务
点击前往腾讯云官网开通,开通后前往控制台获取 secretId
和 secretKey
。
二、安装 PHP SDK
- 在你项目的
composer.json
文件中加入:
{
"require": {
"qcloud/cos-sdk-v5": ">=2.0"
}
}
- 执行
composer install
进行安装。
三、代码实现
<?php
namespace app\api\common\controller;
use Qcloud\Cos\Client;
class Upload
{
private $secretId = ""; // 云 API 密钥 SecretId;
private $secretKey = ""; // 云 API 密钥 SecretKey;
// 上传资源至腾讯云对象存储
public function uploadToTencentCos()
{
$region = "ap-beijing";
// 初始化
$cosClient = new Client(array(
'region' => $region,
'schema' => 'http',
'credentials'=> array(
'secretId' => $this->secretId,
'secretKey' => $this->secretKey
)
));
// 接收文件
$file = $_FILES['file'];
// 重新命名文件
$newName = uniqid().time().strrchr($file['name'], '.');
// 上传资源
$result = $cosClient->putObject(array(
'Bucket' => '', // 你的 bucket 名称
'Key' => $newName,
'Body' => fopen($file['tmp_name'], 'rb'),
'ContentType' => 'image/jpg,image/png,image/jpeg,image/tmp'
));
// 查看结果
print_r($result);
}
}