12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- <?php
- namespace App\DataApiNew\Helper;
- use Qcloud\Cos\Client;
- use Qcloud\Cos\Exception\ServiceResponseException;
- use Illuminate\Support\Facades\Log;
- /**
- * 腾讯云cos 存储桶
- */
- class TencentCosHelper
- {
- public $cosClient;
- public function __construct()
- {
- // SECRETID 和 SECRETKEY 请登录访问管理控制台进行查看和管理
- $secretId = "AKIDsZ2IMEu24wfCbpW2KNFxWwRwNj9VkvDM"; //用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
- $secretKey = "yujR4a9vXxLhw584JOH75tUs34uX3MRJ"; //用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
- $region = "ap-shanghai"; //用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
- $data = [
- 'region' => $region,
- 'schema' => 'https', //协议头部,默认为 http
- 'credentials' => [
- 'secretId' => $secretId,
- 'secretKey' => $secretKey
- ]
- ];
- $this->cosClient = new Client($data);
- }
- /**
- * 上传腾讯存储桶
- *
- * @param [string] $files 文件路径
- * @return array
- */
- public function uploadFiles($files,$key = null)
- {
- try {
- $bucket = 'file-1314054542';
- $key = $key??$files; //文件名
- $local_path = $files;
- $body = fopen($local_path, 'rb');
- $result = $this->cosClient->upload(
- $bucket = $bucket, //存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
- $key = $key, //此处的 key 为对象键
- $body = $body
- );
- return ['code' => 1, 'msg' => '上传成功', 'data' => ['path' => 'https://' . $result['Location']]];
- } catch (ServiceResponseException $e) {
- // 腾讯云COS SDK异常
- Log::error("腾讯云COS上传失败1:".$e);
- return ['code' => 0, 'msg' => '上传失败', 'data' => []];
- } catch (\Exception $e) {
- // 请求失败
- Log::error("腾讯云COS上传失败2:".$e);
- return ['code' => 0, 'msg' => '上传失败', 'data' => []];
- }
- }
-
- //查询对象是否存在
- public function checkFileExist($key)
- {
- try {
- $bucket = 'file-1314054542';
- $result = $this->cosClient->doesObjectExist($bucket, $key);
- if ($result) {
- return ['code' => 1, 'msg' => 'success'];
- } else {
- return ['code' => 0, 'msg' => 'no exist'];
- }
- } catch (\Exception $e) {
- return ['code' => 0, 'msg' => $e->getMessage()];
- }
- }
- //获取对象链接
- public function getFileUrl($key)
- {
- try {
- $bucket = 'file-1314054542';
- // 获取对象链接
- $objectUrl = $this->cosClient->getObjectUrl($bucket, $key);
- return ['code' => 1, 'msg' => 'success','data'=>$objectUrl];
- } catch (\Exception $e) {
- return ['code' => 0, 'msg' => $e->getMessage()];
- }
- }
-
- }
|