Cos技术文档
1、安装phpSdk
通过composer的方式安装。
1.1 在composer.json中添加 qcloud/cos-sdk-v5: >=2.0
"require": {
"php": ">=7.2.5",
"topthink/framework": "^6.1.0",
"topthink/think-orm": "^2.0",
"topthink/think-filesystem": "^1.0",
"zoujingli/wechat-developer": "^1.2",
"qcloud/cos-sdk-v5": ">=2.0"
},
将composer.lock删除,然后运行composer install 就安装成功了。
查看vendor中的是否存在qcloud\cos-sdk-v5,安装包中有使用的例子:sample文件夹中。
2、添加配置文件
3、编写cos工具类
<?php
namespace app\common;
use think\facade\Config;
use Qcloud\Cos\Client;
class CosClient
{
public static function uploadFile()
{
### 上传文件流
try {
$qcloudConfig = Config::get("cosClient");
$bucket = $qcloudConfig["bucket"]; //存储桶名称 格式:BucketName-APPID
$key = "exampleobject"; //此处的 key 为对象键,对象键是对象在存储桶中的唯一标识
$srcPath = "C:/Users/nima/Desktop/Snipaste_2023-07-26_14-59-39.png"; //本地文件绝对路径
$file = fopen($srcPath, 'rb');
if ($file) {
$result = CosClient::cosClient()->Upload(
$bucket = $bucket,
$key = $key,
$body = $file
);
}
print_r($result);
} catch (\Exception $e) {
echo "$e\n";
}
}
public static function cosClient()
{
$qcloudConfig = Config::get("cosClient");
$secretId = $qcloudConfig["secretId"];
$secretKey = $qcloudConfig["secretKey"];
$region = $qcloudConfig["region"];
$cosClient = new Client(
array(
'region' => $region,
'schema' => 'https', //协议头部,默认为http
'credentials' => array(
'secretId' => $secretId,
'secretKey' => $secretKey
)
)
);
return $cosClient;
}
}
测试:
<?php
namespace app\controller;
use app\BaseController;
use think\Request;
use app\model\User;
use think\facade\Config;
use app\common\CosClient;
class CosController extends BaseController
{
/**
* 上传文件cos
*/
public function cosUploadFile()
{
CosClient::uploadFile();
}
}
postman请求:
成功报错:
GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate problem: self signed certificate in certificate
chain (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for
https://shushan-1259593927.cos.ap-nanjing.myqcloud.com/exampleobject in
F:\shushan-server\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:211
Stack trace:
#0 F:\shushan-server\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(158):
GuzzleHttp\Handler\CurlFactory::createRejection()
#1 F:\shushan-server\vendor\guzzlehttp\guzzle\src\Handler\Curl
按照报错指示,查看https://curl.haxx.se/libcurl/c/libcurl-errors.html找到解决办法:
下载pem证书,配置证书。
curl pem证书下载地址
将证书保存在:D:/phpstudy_pro/Extensions/php/php8.0.2nts/extras/ssl/cacert.pem
打开PHP.ini配置文件:配置证书:curl.cainfo
重启小皮
再次postman访问:成功了!