安装 PHPsdk
composer require qcloud/cos-sdk-v5
代码类
<?php
namespace App\Libraries;
require ROOT_PATH . '/vendor/autoload.php';
class HttpUpload
{
/**
* 应用ID
* @var string
*/
public $secretId;
/**
* 应用密钥
* @var string
*/
public $secretKey;
/**
* 存储桶地域
* @var string
*/
public $region;
/**
* 存储桶名称
* @var
*/
public $bucket;
/**
* 本地文件地址
* @var string
*/
public $filePath = '';
public function __construct()
{
$this->secretId = config('app.secret_id');
$this->secretKey = config('app.secret_key');
$this->region = config('app.region');
$this->bucket = config('app.bucket');
}
/**
* 上传本地文件
*/
public function upload()
{
try {
$cosClient = new \Qcloud\Cos\Client(
array(
'region' => $this->region,
'schema' => 'https', //协议头部,默认为http
'credentials'=> array(
'secretId' => $this->secretId ,
'secretKey' => $this->secretKey
)
)
);
$result = $cosClient->putObject(array(
'Bucket' => $this->bucket, //格式:BucketName-APPID
'Key' => 'im/' . basename($this->filePath),
'Body' => fopen($this->filePath, 'rb'),
));
// 请求成功
} catch (\Exception $e) {
// 请求失败
throw new \Exception($e->getMessage());
}
}
/**
* 获取上传文件链接
*/
public function getObjectUrl()
{
try {
$cosClient = new \Qcloud\Cos\Client(
array(
'region' => $this->region,
'schema' => 'https', //协议头部,默认为http
'credentials'=> array(
'secretId' => $this->secretId ,
'secretKey' => $this->secretKey
)
)
);
$key = 'im/' . basename($this->filePath); //对象在存储桶中的位置,即对象键
$signedUrl = $cosClient->getObjectUrl($this->bucket, $key, '+10 minutes'); //签名的有效时间
// 请求成功
} catch (\Exception $e) {
// 请求失败
throw new \Exception($e->getMessage());
}
return $signedUrl;
}
}
使用示例
#上传文件
if(is_file($localFile)) {
$file = new HttpUpload(); # 实例化类
$file->filePath = $localFile;
$file->upload();
}
请成为永远疯狂永远浪漫永远清澈的存在。