chengkun
2025-09-05 4822304b63e1bd6327860af7f3db0133cecf167f
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
<?php
 
namespace common;
 
use think\facade\Config;
require __DIR__ . '/cos-sdk-v5-7.phar';
 
class Uploadcos {
    private $cosClient;
    private $SecretId;
    private $SecretKey;
    private $appId;
    private $region;
    
    
    public function __construct() {
        $this->SecretId = Config::get('qcloud.Qcloud.SecretId');
        $this->SecretKey = Config::get('qcloud.Qcloud.SecretKey');
        $this->appId = Config::get('qcloud.Qcloud.appId');
        $this->region = Config::get('qcloud.Qcloud.region');
        
        $this->cosClient = new \Qcloud\Cos\Client(
            array(
                'region'      => $this->region,
                'scheme'      => 'https', //协议头部,默认为 http
                'credentials' => array(
                    'secretId'  => $this->SecretId,
                    'secretKey' => $this->SecretKey)
            ));
    }
    /*
     * 上传文件
     */
    public function cosUpload($key, $localPath) {
        try {
            $bucket = Config::get('qcloud.Qcloud.bucket'); //存储桶名称 格式:BucketName-APPID
            $result = $this->cosClient->putObject(
                array(
                    'Bucket' => $bucket,
                    'Key'    => $key,
                    'Body'   => fopen($localPath, 'rb')
                ));
            return $result;
            
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
    /*
     * 删除文件
     */
    public function cosDelete($key, $versionId = '') {
        try {
            $bucket = Config::get('qcloud.Qcloud.bucket'); //存储桶名称 格式:BucketName-APPID
            $result = $this->cosClient->deleteObject(
                array(
                    'Bucket'    => $bucket,
                    'Key'       => $key,
                    'VersionId' => $versionId
                ));
            return $result;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
    
    
}