Files
EasyAdmin8/app/admin/service/upload/driver/txcos/Cos.php
wolfcode e1c3216904 init
2023-06-15 16:18:27 +08:00

89 lines
2.3 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\admin\service\upload\driver\txcos;
use EasyAdmin\upload\interfaces\OssDriver;
use Qcloud\Cos\Client;
use think\Exception;
class Cos implements OssDriver
{
protected static $instance;
protected $secretId;
protected $secretKey;
protected $region;
protected $bucket;
protected $schema = 'https';
protected $cosClient;
protected function __construct($config)
{
$this->secretId = $config['txcos_secret_id'];
$this->secretKey = $config['txcos_secret_key'];
$this->region = $config['txcos_region'];
$this->bucket = $config['tecos_bucket'];
$this->cosClient = new Client(
[
'region' => $this->region,
'schema' => $this->schema,
'credentials' => [
'secretId' => $this->secretId,
'secretKey' => $this->secretKey],
]);
return $this;
}
public static function instance($config)
{
if (is_null(self::$instance)) {
self::$instance = new static($config);
}
return self::$instance;
}
public function save($objectName, $filePath)
{
try {
$key = $objectName;
$file = fopen($filePath, "rb");
if ($file) {
$result = $this->cosClient->putObject([
'Bucket' => $this->bucket,
'Key' => $key,
'Body' => $file]
);
// todo 腾讯云坑逼返回保护变量也不提供get方法
$result = (array)$result;
$result = $result['*data'];
} else {
throw new Exception('文件信息有误');
}
} catch (\Exception $e) {
return [
'save' => false,
'msg' => $e->getMessage(),
];
}
if (!isset($result['Location'])) {
return [
'save' => false,
'msg' => '保存失败',
];
}
return [
'save' => true,
'msg' => '上传成功',
'url' => $this->schema . '://' . $result['Location'],
];
}
}