Files
yusheng-php/application/common/controller/Upload.php

84 lines
2.5 KiB
PHP
Raw Normal View History

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