文件上传

This commit is contained in:
2025-10-23 17:11:45 +08:00
parent 828bf74397
commit 791562cfd3
2 changed files with 74 additions and 10 deletions

View File

@@ -0,0 +1,20 @@
<?php
namespace app\api\controller;
use app\common\controller\BaseCom;
use app\common\controller\Upload as UploadFile;
class Upload extends BaseCom
{
//获取上传文件的临时秘钥
public function getTempKeys()
{
$upload = new UploadFile();
$reslut = $upload->getTempCredential();
return V($reslut['code'], $reslut['msg'], $reslut['data']);
}
}

View File

@@ -6,6 +6,7 @@ use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
use Qcloud\Cos\Client;
use QCloud\COSSTS\Sts;
class Upload
{
@@ -22,10 +23,11 @@ class Upload
$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->region = get_system_config_value('cos_region');
$this->cosId = get_system_config_value('cos_id');
$this->cosSecret = get_system_config_value('cos_secret');
$this->cosbucket= get_system_config_value('cos_bucket_name');
$this->url= get_system_config_value('cos_http_url');
//获取配置
$this->ossClient = new OssClient(
$ossId,
@@ -35,10 +37,10 @@ class Upload
// 初始化COS客户端
$this->cosClient = new Client([
'region' => $region, // 你的存储桶所属地域,如 `ap-guangzhou`
'region' => $this->region, // 你的存储桶所属地域,如 `ap-guangzhou`
'credentials' => [
'secretId' => $cosId,
'secretKey' => $cosSecret,
'secretId' => $this->cosId,
'secretKey' => $this->cosSecret,
],
]);
}
@@ -70,14 +72,56 @@ class Upload
try {
$result = $this->cosClient->putObject([
'Bucket' => $this->cosbucket,
'Key' => $object,
'Key' => 'admin/'.$object,
'Body' => fopen($filePath, 'rb'),
]);
// 上传成功,可以处理$result
return $result['ObjectURL']; // 或根据你的需要拼接访问URL
// var_dump($result);exit; cos_http_url
return $this->url.'/'.$result['Key']; // 或根据你的需要拼接访问URL
} catch (OssException $e) {
return false; // 上传失败返回false并记录错误信息例如echo $e->getMessage();
return $e->getMessage(); // 上传失败返回false并记录错误信息例如echo $e->getMessage();
}
}
/*
* 获取腾讯COS临时密钥
*/
public function getTempCredential()
{
try {
$sts = new Sts();
$tempKeys = $sts->getTempKeys([
'url' => 'https://sts.tencentcloudapi.com/',
'domain' => 'sts.tencentcloudapi.com',
'proxy' => '',
'secretId' => $this->cosId,
'secretKey' => $this->cosSecret,
'bucket' => $this->cosbucket,
'region' => $this->region,
'durationSeconds' => 7200,
'allowActions' => [
// 所有 COS 操作,可根据需要限定为具体操作,如 'cos:PutObject'
'cos:*'
],
'allowPrefix' => ['images/*'], // 可进一步限制前缀
]);
return [
'code' => 1,
'msg' => 'success',
'data' => [
'credentials' => $tempKeys['credentials'],
'startTime' => $tempKeys['startTime'],
'expiredTime' => $tempKeys['expiredTime'],
'region' => $this->region,
'bucket' => $this->cosbucket,
]
];
} catch (\Exception $e) {
return ['code' => 0, 'msg' => '临时密钥获取失败: ' . $e->getMessage()];
}
}