I. New TP6 project
(1) environment
- PHP7+
- composer
(2) new
- Note: long installation time, available domestic mirror
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
Copy the code
- Tx-cloud is a customizable project name
composer create-project topthink/think tx-cloud
Copy the code
2. Install object storage COS
(1) Modify composer. Json
{
"require": {
"qcloud/cos-sdk-v5": "> = 2.0"}}Copy the code
(2) Run the command
composer update
Copy the code
composer install
Copy the code
(3) Check whether the installation is complete
Check whether qCloud exists in the vendor directory
3. Use cloud storage
(1) Complete code
/ / code path: / project name/app/controller/index. The PHP
namespace app\controller;
use app\BaseController;
use Qcloud\Cos\Client;
class Index extends BaseController
{
private $secretId = "Your cloud API key SecretId"; //" cloud API key SecretId";
private $secretKey = "Your API SecretKey."; //" cloud API SecretKey";
private $region = "Your bucket territory"; // Set a default bucket region
private $bucket = "Your bucket name"; // BucketName format: bucketname-appid
private function __cosClient(){
return $cosClient = new Client(
array(
'schema'= >'http'.// The protocol header, which defaults to HTTP
'region'= >$this->region,
'credentials'= >array(
'secretId'= >$this->secretId ,
'secretKey'= >$this->secretKey
)
)
);
}
public function upload()
{
// Get the uploaded file
$file = request()->file('file');
// Get the bucket object
$cosClient = $this->__cosClient();
/ / upload
try {
$result = $cosClient->Upload(
$bucket = $this->bucket,// Bucket name
$key = 'images/'.md5(uniqid()).'. '.pathinfo($file->getOriginalName(), PATHINFO_EXTENSION), // Key is the object key
$body = fopen($file->getFileInfo()->getPathname(), "rb")// File data
);
// The request succeeded
return json([
"msg"= >"Upload successful"."data"= > ["RequestId"= >$result['RequestId']."Bucket"= >$result['Bucket']."Key"= >$result['Key']."Location"= >$result['Location']]]); }catch (\Exception $e) {
// The request failed
return json([
"msg"= >"Upload failed"."data"=>[],
]);
//echo $e;}}public function delete(){
// Get the key for the deleted graph
$key = input('get.') ['key'];
// Get the bucket object
$cosClient = $this->__cosClient();
/ / delete
try {
$result = $cosClient->deleteObject(array(
'Bucket'= >$this->bucket,// Bucket name
'Key'= >$key));// The request succeeded
return json([
"msg"= >"Deleted successfully"."data"= > ["RequestId"= >$result['RequestId']."Bucket"= >$result['Bucket']."Key"= >$result['Key']."Location"= >$result['Location']]]); }catch (\Exception $e) {
// The request failed
return json([
"msg"= >"Delete failed"."data"=>[],
]);
//echo $e;}}}Copy the code