1.创建一个名为 composer.json
的文件,内容如下:
{
"require": {
"qcloud/cos-sdk-v5": ">=2.0"
}
}
2.执行以下命令,使用 Composer 安装。
php composer update
3.复制代码 我这里目录结构是 app\common\service
<?php
declare (strict_types = 1);
namespace app\common\service;
use Qcloud\Cos\Client;
use Qcloud\Cos\Exception\ServiceResponseException;
use think\Exception;
class TencentUpload
{
// $srcPath 本地文件绝对路径
// $type 文件mime类型
// $dir 远程目录
public static function upload($srcPath,$type,$dir)
{
// 腾讯云账户中的SecretId
$SecretId = '************';
// 腾讯云账户中的SecretKey
$SecretKey = '**********';
$region = "******"; //设置一个默认的存储桶地域
$array =array(
'region' => $region,
'schema' => 'https', //协议头部,默认为http
'credentials'=> array(
'secretId' => $SecretId,
'secretKey' => $SecretKey,
)
);
$cosClient= new Client($array);
$keyv = $dir.'/'.random(32); //随机文件名
try {
$bucket = "*********"; //存储桶名称 格式:BucketName-APPID
$key = $keyv; //此处的 key 为对象键,对象键是对象在存储桶中的唯一标识
$file = fopen($srcPath, "rb");
if($file){
try {
$result = $cosClient->putObject(
array(
'Bucket' => $bucket,
'Key' => $key,
'Body' => $file,//文件路径
'ContentType' => $type//文件类型
)
);
return json_encode(["code"=>0,"msg"=>'成功','data'=>'https://'.$result['Location']]);
}catch (ServiceResponseException $e){
return json_encode(["code"=>-1,"msg"=>$e->getMessage()]);
}
}else{
return json_encode(["code"=>-1,"msg"=>'非法文件']);
}
}catch (\Exception $e){
return json_encode(["code"=>-1,"msg"=>$e->getMessage()]);
}
}
}
4.使用
$file = request()->file('file');
try {
validate(['image'=>'filesize:10240|fileExt:jpg,png,jpeg'])
->check([$file]);
if($file){
//传临时目录以及mime类型以及创建远程目录
$res = \app\common\service\TencentUpload::upload($file->getPathname(),$file->getMime(),"pic1");
}else{
return Resultsfail([-1,$file->getError()]);
}
} catch (\think\exception\ValidateException $e) {
return Resultsfail([-1,$e->getMessage()]);
}