quanwei
2025-11-01 121b714d710cf3c865f4a1b5efe81abec11056d1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
 
namespace app\common\library\storage\engine;
 
use Qcloud\Cos\Client;
 
/**
 * 腾讯云存储引擎 (COS)
 */
class Qcloud extends Server
{
    private $config;
    private $cosClient;
 
    /**
     * 构造方法
     */
    public function __construct($config)
    {
        parent::__construct();
        $this->config = $config;
        // 创建COS控制类
        $this->createCosClient();
    }
 
    /**
     * 创建COS控制类
     */
    private function createCosClient()
    {
        $this->cosClient = new Client([
            'region' => $this->config['region'],
            'credentials' => [
                'secretId' => $this->config['secret_id'],
                'secretKey' => $this->config['secret_key'],
            ],
        ]);
    }
 
    /**
     * 执行上传
     */
    public function upload()
    {
        // 上传文件
        // putObject(上传接口,最大支持上传5G文件)
        try {
            $this->cosClient->putObject([
                'Bucket' => $this->config['bucket'],
                'Key' => $this->fileName,
                'Body' => fopen($this->getRealPath(), 'rb')
            ]);
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }
 
    /**
     * 删除文件
     */
    public function delete($fileName)
    {
        try {
            $result = $this->cosClient->deleteObject(array(
                'Bucket' => $this->config['bucket'],
                'Key' => $fileName
            ));
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }
 
    /**
     * 返回文件路径
     */
    public function getFileName()
    {
        return $this->fileName;
    }
 
}