Files
yusheng-php/application/common/controller/Upload.php
2025-10-23 11:25:40 +08:00

84 lines
2.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

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\common\controller;
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
use Qcloud\Cos\Client;
class Upload
{
// 显式声明属性
private $config;
private $ossClient; // 修复点:添加该属性声明
private $bucket;
private $cosbucket;
public function __construct()
{
// $this->config = get_system_config();
$endpoint = get_system_config_value('oss_region_url');
$this->bucket= get_system_config_value('oss_bucket_name');
$ossId = get_system_config_value('oss_access_key_id');
$ossSecret = get_system_config_value('oss_access_key_secret');
$region = get_system_config_value('cos_region');
$cosId = get_system_config_value('cos_id');
$cosSecret = get_system_config_value('cos_secret');
$this->cosbucket= get_system_config_value('cos_bucket_name');
//获取配置
$this->ossClient = new OssClient(
$ossId,
$ossSecret,
$endpoint
);
// 初始化COS客户端
$this->cosClient = new Client([
'region' => $region, // 你的存储桶所属地域,如 `ap-guangzhou`
'credentials' => [
'secretId' => $cosId,
'secretKey' => $cosSecret,
],
]);
}
/*
* 上传文件 -阿里oss
* 参数:
* $bucket: 存储空间名称
* $object: 文件名
* $filePath: 文件路径
* 返回:
* true: 上传成功
* false: 上传失败
*/
public function uploadFile($object, $filePath) {
try {
$result = $this->ossClient->uploadFile($this->bucket, $object, $filePath);
return true; // 上传成功返回true
} catch (OssException $e) {
return false; // 上传失败返回false并记录错误信息例如echo $e->getMessage();
}
}
/*
* 上传文件 -腾讯cos
*/
public function uploadFileCos($object, $filePath) {
try {
$result = $this->cosClient->putObject([
'Bucket' => $this->cosbucket,
'Key' => $object,
'Body' => fopen($filePath, 'rb'),
]);
// 上传成功,可以处理$result
return $result['ObjectURL']; // 或根据你的需要拼接访问URL
} catch (OssException $e) {
return false; // 上传失败返回false并记录错误信息例如echo $e->getMessage();
}
}
}