<?php
namespace CrsSdk\Common;
use App\Exceptions\Error;
use Qcloud\Cos\Client;
class QCloudCos
{
/**
* 腾讯云上传对象实例
*
* @var Client
*/
protected $cosClient;
/**
* 存储桶名称
*
* @var mixed
*/
protected $bucket;
/**
* 环境域名
*
* @var mixed
*/
protected $host;
/**
* QCloudCos constructor.
*/
public function __construct()
{
$config = $this->getConfig();
$this->cosClient = new Client([
'region' => $config['region'],
'schema' => $config['schema'],
'credentials'=> [
'secretId' => $config['secretId'],
'secretKey' => $config['secretKey']
]
]);
$this->bucket = $config['bucket'];
$this->host = $config['host_url'];
}
/**
* 读取配置文件
*
* @return mixed
*/
private function getConfig()
{
$config = config('third_party.QCloudCos');
if (empty($config) || !is_array($config)) {
throw new Error(100000, 'QCloudCos配置文件错误,请检查配置文件');
}
return $config;
}
/**
* 上传文件
*
* @param object $file 文件资源
*
* @return mixed
*/
public function upload($file)
{
$filePath = $file->path();
$key = date('Y/m/d/', time()) . md5(uniqid()) . '.' . $file->getClientOriginalExtension();
try {
$result = $this->cosClient->putObject([
'Bucket' => $this->bucket,
'Key' => $key,
'Body' => fopen($filePath, 'rb'),
])->toArray();
$url = explode('/', $result['ObjectURL']);
$url[2] = $this->host;
} catch (\Exception $exception) {
throw new Error(100000, '图片上传失败');
}
return implode('/', $url);
}
/**
* 通过文件url地址上传文件
*
* @param $imageUrl
*
* @return string
*/
public function uploadImageUrl($imageUrl){
$key = date('Y/m/d/', time()) . md5(uniqid()).'.png';
try {
$result = $this->cosClient->putObject([
'Bucket' => $this->bucket,
'Key' => $key,
'Body' => file_get_contents($imageUrl),
])->toArray();
$url = explode('/', $result['ObjectURL']);
$url[2] = $this->host;
} catch (\Exception $exception) {
//throw new Error(100000, '图片上传失败');
return '';
}
return implode('/', $url);
}
public function uploadPath($path){
$key = date('Y/m/d/', time()) . md5(uniqid()).'.png';
try {
$result = $this->cosClient->putObject([
'Bucket' => $this->bucket,
'Key' => $key,
'Body' => file_get_contents($path),
])->toArray();
$url = explode('/', $result['ObjectURL']);
$url[2] = $this->host;
} catch (\Exception $exception) {
//throw new Error(100000, '图片上传失败');
return '';
}
return implode('/', $url);
}
}
QCloudCos.php
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。