一、新建TP6项目
(1)环境
- PHP7+
- composer
(2)新建
- 注:安装时间长,可用国内镜像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
复制代码
- tx-cloud是项目名称可自定义
composer create-project topthink/think tx-cloud
复制代码
二、安装对象存储 COS
(1)修改composer.json
{
"require": {
"qcloud/cos-sdk-v5": ">=2.0"
}
}
复制代码
(2)运行命令
composer update
复制代码
composer install
复制代码
(3)检查是否安装
vendor目录下是否存在qcloud
三、使用云存储
(1)完整代码
<?php
//代码路径:/项目名/app/controller/index.php
namespace app\controller;
use app\BaseController;
use Qcloud\Cos\Client;
class Index extends BaseController
{
private $secretId = "你的云 API 密钥 SecretId"; //"云 API 密钥 SecretId";
private $secretKey = "你的API 密钥 SecretKey"; //"云 API 密钥 SecretKey";
private $region = "你的存储桶地域"; //设置一个默认的存储桶地域
private $bucket = "你的存储桶名称"; //存储桶名称 格式:BucketName-APPID
private function __cosClient(){
return $cosClient = new Client(
array(
'schema' => 'http', //协议头部,默认为http
'region' => $this->region,
'credentials'=> array(
'secretId' => $this->secretId ,
'secretKey' => $this->secretKey
)
)
);
}
public function upload()
{
//获取上传的文件
$file = request()->file('file');
//获取储存桶对象
$cosClient = $this->__cosClient();
//上传
try {
$result = $cosClient->Upload(
$bucket = $this->bucket,//存储桶名称
$key = 'images/'.md5(uniqid()).'.'.pathinfo($file->getOriginalName(), PATHINFO_EXTENSION), //此处的 key 为对象键
$body = fopen($file->getFileInfo()->getPathname(), "rb")//文件数据
);
// 请求成功
return json([
"msg"=>"上传成功",
"data"=>[
"RequestId"=>$result['RequestId'],
"Bucket"=>$result['Bucket'],
"Key"=>$result['Key'],
"Location"=>$result['Location'],
]
]);
} catch (\Exception $e) {
// 请求失败
return json([
"msg" =>"上传失败",
"data"=>[],
]);
//echo $e;
}
}
public function delete(){
//获取删除图的key
$key = input('get.')['key'];
//获取储存桶对象
$cosClient = $this->__cosClient();
//删除
try {
$result = $cosClient->deleteObject(array(
'Bucket' => $this->bucket,//存储桶名称
'Key' => $key,
));
// 请求成功
return json([
"msg"=>"删除成功",
"data"=>[
"RequestId"=>$result['RequestId'],
"Bucket"=>$result['Bucket'],
"Key"=>$result['Key'],
"Location"=>$result['Location'],
]
]);
} catch (\Exception $e) {
// 请求失败
return json([
"msg" =>"删除失败",
"data"=>[],
]);
//echo $e;
}
}
}
复制代码
至此就可以使用upload上传图片,delete删除图片。
本文演示视频:点击浏览
更多前端内容欢迎关注公众号:天小天个人网
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END