本文目录导读:

我来详细说明PHP项目对接腾讯云COS的完整流程。
前期准备
1 开通COS服务
- 登录 腾讯云控制台
- 进入对象存储COS服务
- 创建存储桶(Bucket)
- 获取以下信息:
- SecretId
- SecretKey
- Bucket名称
- 所属地域(Region)
安装SDK
使用Composer安装
composer require qcloud/cos-sdk-v5
或手动下载
从 GitHub 下载源码
基础配置
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Qcloud\Cos\Client;
class CosService
{
private $cosClient;
private $bucket;
private $region;
public function __construct()
{
$secretId = 'your_secret_id'; // 替换为你的SecretId
$secretKey = 'your_secret_key'; // 替换为你的SecretKey
$this->region = 'ap-guangzhou'; // 替换为你的区域
$this->bucket = 'examplebucket-1250000000'; // 替换为你的Bucket
$this->cosClient = new Client([
'region' => $this->region,
'schema' => 'https', // 使用HTTPS
'credentials' => [
'secretId' => $secretId,
'secretKey' => $secretKey,
],
]);
}
文件上传
1 简单上传
// 上传本地文件
public function uploadFile($localPath, $cosPath)
{
try {
$result = $this->cosClient->putObject([
'Bucket' => $this->bucket,
'Key' => $cosPath,
'Body' => fopen($localPath, 'rb'),
'ACL' => 'public-read', // 设置访问权限
]);
// 生成访问URL
$url = $this->getObjectUrl($cosPath);
return [
'success' => true,
'url' => $url,
'etag' => $result['ETag'],
];
} catch (\Exception $e) {
return [
'success' => false,
'message' => $e->getMessage(),
];
}
}
2 分片上传(大文件)
// 分片上传大文件
public function uploadLargeFile($localPath, $cosPath)
{
try {
$result = $this->cosClient->upload(
$bucket = $this->bucket,
$key = $cosPath,
$body = fopen($localPath, 'rb'),
$options = [
'ACL' => 'public-read',
'partSize' => 10 * 1024 * 1024, // 分片大小10MB
'concurrency' => 3, // 并发数
]
);
return [
'success' => true,
'location' => $result['Location'],
];
} catch (\Exception $e) {
return [
'success' => false,
'message' => $e->getMessage(),
];
}
}
3 上传文件流
// 直接上传内容
public function uploadContent($content, $cosPath)
{
try {
$result = $this->cosClient->putObject([
'Bucket' => $this->bucket,
'Key' => $cosPath,
'Body' => $content,
]);
return [
'success' => true,
'url' => $this->getObjectUrl($cosPath),
];
} catch (\Exception $e) {
return [
'success' => false,
'message' => $e->getMessage(),
];
}
}
文件下载
1 下载到本地
public function downloadFile($cosPath, $localPath)
{
try {
$result = $this->cosClient->getObject([
'Bucket' => $this->bucket,
'Key' => $cosPath,
'SaveAs' => $localPath,
]);
return [
'success' => true,
'contentType' => $result['ContentType'],
'contentLength' => $result['ContentLength'],
];
} catch (\Exception $e) {
return [
'success' => false,
'message' => $e->getMessage(),
];
}
}
2 生成临时下载URL
public function getObjectUrl($cosPath, $expireTime = 3600)
{
try {
// 获取对象URL
$url = $this->cosClient->getObjectUrl(
$this->bucket,
$cosPath,
$expireTime // 过期时间(秒)
);
return $url;
} catch (\Exception $e) {
return false;
}
}
文件管理
1 删除文件
public function deleteFile($cosPath)
{
try {
$result = $this->cosClient->deleteObject([
'Bucket' => $this->bucket,
'Key' => $cosPath,
]);
return ['success' => true];
} catch (\Exception $e) {
return [
'success' => false,
'message' => $e->getMessage(),
];
}
}
2 批量删除
public function batchDeleteFiles($cosPaths)
{
try {
$objects = [];
foreach ($cosPaths as $path) {
$objects[] = ['Key' => $path];
}
$result = $this->cosClient->deleteObjects([
'Bucket' => $this->bucket,
'Objects' => $objects,
]);
return ['success' => true];
} catch (\Exception $e) {
return [
'success' => false,
'message' => $e->getMessage(),
];
}
}
3 文件列表
public function listFiles($prefix = '', $maxKeys = 100)
{
try {
$result = $this->cosClient->listObjects([
'Bucket' => $this->bucket,
'Prefix' => $prefix,
'MaxKeys' => $maxKeys,
]);
$files = [];
if (isset($result['Contents'])) {
foreach ($result['Contents'] as $content) {
$files[] = [
'key' => $content['Key'],
'size' => $content['Size'],
'lastModified' => $content['LastModified'],
'etag' => $content['ETag'],
];
}
}
return [
'success' => true,
'files' => $files,
'isTruncated' => $result['IsTruncated'],
];
} catch (\Exception $e) {
return [
'success' => false,
'message' => $e->getMessage(),
];
}
}
图片处理
// 图片处理(缩放、裁剪等)
public function processImage($cosPath, $operations)
{
// 示例:缩略图
$imageParams = [
'ci-process' => 'imageMogr2',
'thumbnail' => '!200x200r', // 缩放为200x200
'format' => 'jpg',
];
$url = $this->getObjectUrl($cosPath) . '?' . http_build_query($imageParams);
return $url;
}
完整示例
<?php
// index.php - 完整使用示例
require_once 'CosService.php';
$cosService = new CosService();
// 上传文件
$result = $cosService->uploadFile(
'/path/to/local/file.jpg', // 本地文件路径
'images/2024/01/01/file.jpg' // COS中路径
);
if ($result['success']) {
echo "上传成功!URL: " . $result['url'];
} else {
echo "上传失败: " . $result['message'];
}
// 下载文件
$downloadResult = $cosService->downloadFile(
'images/2024/01/01/file.jpg',
'/path/to/download/file.jpg'
);
// 生成临时URL(7天有效)
$tempUrl = $cosService->getObjectUrl(
'images/2024/01/01/file.jpg',
7 * 24 * 3600
);
echo "临时访问URL: " . $tempUrl;
最佳实践
1 配置文件示例
<?php
// config/cos.php
return [
'secret_id' => env('COS_SECRET_ID', ''),
'secret_key' => env('COS_SECRET_KEY', ''),
'region' => env('COS_REGION', 'ap-guangzhou'),
'bucket' => env('COS_BUCKET', ''),
'schema' => 'https',
'read_write_timeout' => 60,
'timeout' => 60,
];
2 异常处理
use Qcloud\Cos\Exception\ServiceResponseException;
try {
// COS操作
} catch (ServiceResponseException $e) {
// 服务端错误
$statusCode = $e->getStatusCode();
$errorCode = $e->getCosErrorCode();
$errorMessage = $e->getCosErrorMessage();
$requestId = $e->getCosRequestId();
Log::error("COS Error: {$errorCode} - {$errorMessage}");
} catch (\Exception $e) {
// 其他错误
Log::error("COS Error: " . $e->getMessage());
}
3 性能优化建议
- 使用连接池:复用客户端实例
- 设置超时时间:
'timeout' => 60, 'connect_timeout' => 10,
- 大文件分片上传:超过5MB建议使用分片
- 设置缓存策略:合理设置Cache-Control
这样就完成了PHP项目对接腾讯云COS的完整配置和实现,记得将敏感信息存储在环境变量或配置文件中,不要硬编码在代码中。