chengkun
2025-04-18 1bb985f32f2efe0f9dd69f3cf29a1c809b1cf96d
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<?php
/*
* $Author :PHPYUN开发团队
*
* 官网: http://www.phpyun.com
*
* 版权所有 2009-2021 宿迁鑫潮信息技术有限公司,并保留所有权利。
*
* 软件声明:未经授权前提下,不得用于商业运营、二次开发以及任何形式的再次发布。
 */
 
require_once 'autoload.php';
require_once 'Config.php';
 
use OSS\OssClient;
use OSS\Core\OssException;
 
 
class ossUpload {
    
    const endpoint = Config::OSS_ENDPOINT;// img.douxu.com 图片服务器别名路径 
    const accessKeyId = Config::OSS_ACCESS_ID; //阿里OSS ACCESS
    const accessKeySecret = Config::OSS_ACCESS_KEY;//阿里OSS ACCESSkey
    const bucket = Config::OSS_TEST_BUCKET; //BUCKET 名称 即目录 或者 盘符
    const userdomain = Config::OSS_USERDOMAIN; //图片配置域名(远程OSS 地址 image.douxu.com)
    
    private $ossClient;
    private $maxsize;
    private $pic_type;
    private $is_picself;
    private $is_picthumb;
        
    
    function __construct($paras = array()){
        
        $this->maxsize      =  $paras['maxsize'];      // 上传大小
        $this->pic_type     =  $paras['pic_type'];     // 图片类型
        $this->is_picself   =  $paras['is_picself'];   // 安全验证
        $this->is_picthumb  =  $paras['is_picthumb'];  // 强制压缩
        //实例化 ossClient true为开启CNAME。CNAME是指将自定义域名绑定到存储空间上。
        $this->ossClient    =  new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
    }
    /**
     * 上传本地图片至 OSS 
     * $file 本地文件路径
     * $dir  OSS 目录名称
     * $type 后缀名
     * $thumb array  crop 将图最长边限制在 100 像素,短边按比例处理
     */
    public function uploadImg($file,$dir='img',$thumb=array()){
        
        //根据本地文件路径获取后缀名
        $imgType=end(@explode('.',$file['name']));
        //判断后缀名是否合法
        if(!$file['tmp_name']){
 
            $returnMsg['msg'] = '未找到相关图片';
 
        }elseif(!in_array(strtolower($imgType),$this->pic_type)){
            
            $returnMsg['msg'] = '上传文件类型不符';
        
        }elseif($file['size'] > $this->maxsize * 1024){//判断大小是否超限
            
            $returnMsg['msg'] = '上传图片太大';
        
        }else{
            if($dir){
                $dir.='/'.date('Ymd').'/';
            }
 
            //重置文件名称 时间戳+随机数
            $newImgName =time().rand(1000,9999).'.'.$imgType;
            
            $object = $dir.$newImgName;//OSS 新文件名称 可带目录 如 user com 。。
            
            $filePath = $file['tmp_name'];//本地上传文件路径
            
            try {
                $this->ossClient->uploadFile(self::bucket, $object, $filePath);
                //是否需要缩略 按传入长度取最长边长度,短边等比例压缩。
                if(!empty($thumb['crop'])){
                    // 图片缩放
                    $newImgName =time().rand(1000,9999).'.'.$imgType;
                    
                    $Newobject = $dir.$newImgName;//OSS 新文件名称 
                    // 缩放图片格式。等比例缩放,最长边未$fbl
                    $style = "image/resize,l_". $thumb['crop'];
                    // 将处理后的图片转存到当前Bucket。
                    $process = $style. '|sys/saveas' . ',o_'.$this->base64url_encode($Newobject) . ',b_'.$this->base64url_encode(self::bucket);
                    
                    $this->ossClient->processObject(self::bucket, $object, $process);
                    
                    $this->delObject($object);
                    
                    $object  =  $Newobject;
                }
                if (strpos($dir, 'logo') !== false){
                    $returnMsg['picurl'] = $object;
                }else{
                    $returnMsg['picurl'] = './'.$object;
                }
                return $returnMsg;
 
            } catch (OssException $e) {
                //错误信息输出
                $returnMsg['msg'] = $e->getMessage();
            }
        }
        return $returnMsg;
    }
    
 
    /**
     * 上传本地文件至 OSS 
     * $file 本地文件路径
     * $dir  OSS 目录名称
     */
    public function uploadDoc($file,$dir='doc'){
 
        //允许上传文件后缀
        $upTypes=array('doc','docx','rar','zip','txt','xls');
        
        //根据本地文件路径获取后缀名
        $docType=end(@explode('.',$file['name']));
        //判断后缀名是否合法
        if(!$file['tmp_name']){
 
            $returnMsg['error'] = '未找到相关文件';
 
        }elseif(!in_array(strtolower($docType),$upTypes)){
            
            $returnMsg['error'] = '仅允许上传 doc,docx,xls,rar,zip,txt格式文件';
        
        }elseif($file['size']>10*1024*1024){//判断大小是否超限 限定10M
            
            $returnMsg['error'] = '上传文件大小不能超过10M';
        
        }else{
            if($dir){
                $dir.='/'.date('Ymd').'/';
            } 
            //重置文件名称 时间戳+随机数
            $newDocName =time().rand(1000,9999).'.'.$docType;
            
            $object = $dir.$newDocName;//OSS 新文件名称 可带目录
             
            
            $filePath = $file['tmp_name'];//本地上传文件路径
            $options = array();//暂不需要,为空即可
            
            try {
                $this->ossClient->uploadFile(self::bucket, $object, $filePath, $options);
                $returnMsg['docurl'] = '/'.$object;
                
            } catch (OssException $e) {
                //错误信息输出
                $returnMsg['msg'] = $e->getMessage();
                
            }
            return $returnMsg;
        }
        
    }
    /*删除文件
     *$fileUrl:OSS 文件存储地址 如 img/xxxx.jpg
     *$fileUrl: array 可传入数组形式 多文件删除
 
    */
    public function delObject($fileUrl)
    {
        //批量删除多文件
        if(is_array($fileUrl)){
            $object=array();
            foreach($fileUrl as $value){
            //判断是否存储的缩略图格式 即带@ 符号
                if(strstr($value,'@')){
                    $fileUrls = explode('@',$value);
                    $object[] = $fileUrls[0];
                }else{
                    $object[] = $value;
                }
            }
            if($object&&is_array($object)){
                foreach($object as $k=>$v){
                    $v=str_replace('//','',$v);
                    if(substr($v,0,1)=='/'){
                        $v=substr($v,1);
                    }
                    $object[$k]=$v;
                }
            }
            try{
                $this->ossClient->deleteObjects(self::bucket, $object);
 
                return true;
 
            } catch(OssException $e) {
 
                //return $returnMsg['error'] = $e->getMessage();//失败具体原因 仅供调试需要
                return false;
                
            }
        }else{
        
            //判断是否存储的缩略图格式 即带@ 符号
            if(strstr($fileUrl,'@')){
                $fileUrls = explode('@',$fileUrl);
                $object = $fileUrls[0];
            }else{
                $object = $fileUrl;
            }
            $object=str_replace('//','',$object);
            if(substr($object,0,1)=='/'){
                $object=substr($object,1);
            }
            try{
                $this->ossClient->deleteObject(self::bucket, $object);
 
                return true;
 
            } catch(OssException $e) {
 
                //return $returnMsg['error'] = $e->getMessage();//失败具体原因 仅供调试需要
                return false;
                
            }
        }
    }
    /*OSS 同项目内文件复制 
    * $from_object:源文件
    * $to_object :复制后新文件
    */
    function copyObject($from_object, $to_object)
    {
        $to_object=str_replace('//','',$to_object);
        if(substr($to_object,0,1)=='/'){
            $to_object=substr($to_object,1);
        }
        $options = array();
        try{
            $this->ossClient->copyObject(self::bucket, $from_object, self::bucket, $to_object, $options);
 
 
            //return $returnMsg['error'] = 'ok';
            return true;
        } catch(OssException $e) {
 
            //return $returnMsg['error'] = $e->getMessage();
            return false;
        }
    }
    //图片裁剪 缩放 水印 等
    function cutPic($img,$dir,$x,$y,$width,$height,$scale=1){        
        
        $object = $dir.'/'.date('Ymd').'/'.end(explode('/',$img));
 
        //图片裁剪
        if($dir){
            $dir.='/'.date('Ymd').'/';
        } 
        $imgType=end(@explode('.',$object));
        //重置文件名称 时间戳+随机数
        $newImgName =time().rand(1000,9999).'.'.$imgType;
    
        $file = $dir.$newImgName;//OSS 新文件名称 可带目录
    
        try {
            // 自定义裁剪
            $style = 'image/crop,w_'.$width.',h_'.$height.',x_'.$x.',y_'.$y;
            // 将处理后的图片转存到当前Bucket。
            $process = $style. '|sys/saveas' . ',o_'.$this->base64url_encode($file) . ',b_'.$this->base64url_encode(self::bucket);
            
            $this->ossClient->processObject(self::bucket, $object, $process);
            
            $returnMsg['picurl'] = './'.$file;
 
            $this->delObject($object);
            return $returnMsg;
        } catch (OssException $e) {
            
            //错误信息输出
            $returnMsg['error'] = $e->getMessage();
            
            return $returnMsg;
        }
    }
    /**
     * base64图片上传
     * @param string $data  base64
     * @param string $dir   上传位置
     * @return string
     */
    function imageBase($data, $dir = 'img'){
        
        preg_match('/^(data:\s*image\/(\w+);base64,)/', $data, $result);
        
        $uimage = str_replace($result[1], '', str_replace('#','+',$data));
        // 获取图片格式
        if(in_array(strtolower($result[2]),$this->pic_type)){
            $imgType  = $result[2];
        }else{
            $imgType  =  'jpg';
        }
        $new_file = time().rand(1000,9999).'.' . $imgType;
        
        try {
            $objdir = $dir.'/'.date('Ymd').'/';
            $object = $objdir.$new_file;
            // 使用字符串上传,将base64写到图片里
            $this->ossClient->putObject(self::bucket, $object, base64_decode($uimage));
            
            if (strpos($dir, 'logo') !== false){
                $returnMsg['picurl'] = $object;
            }else{
                $returnMsg['picurl'] = './'.$object;
            }
            
        } catch (OssException $e) {
            //错误信息输出
            $returnMsg['msg'] = $e->getMessage();
        }
        
        return $returnMsg;
    }
    /**
     * 上传本地图片至 OSS,用户编辑器内图片上传
     * $file 本地文件路径
     */
    public function uploadLocalImg($file)
    {
        if (strpos($file, 'data/upload') !== false){
            
            $object  =  strstr($file, 'data/upload');
 
            try {
                
                $this->ossClient->uploadFile(self::bucket, $object, $file);
                
                $returnMsg['picurl'] = './'.$object;
                
            } catch (OssException $e) {
                //错误信息输出
                $returnMsg['msg'] = $e->getMessage();
                
            }
            return $returnMsg;
        }
    }
    public function uploadVoice($file,$dir='voice'){
 
        
        $fileType=end(@explode('.',$file['name']));
        if(!$file['tmp_name']){
 
            $returnMsg['msg'] = '录音文件不存在,请重试';
 
        }else{
            if($dir){
                $dir.='/'.date('Ymd').'/';
            } 
            $newVoiceName =time().rand(1000,9999).'.'.$fileType;
            
            $object = $dir.$newVoiceName;
             
            
            $filePath = $file['tmp_name']; 
            $options = array(); 
            
            try {
                $this->ossClient->uploadFile(self::bucket, $object, $filePath, $options);
                $returnMsg['voiceurl'] = '/'.$object;
                
            } catch (OssException $e) {
                $returnMsg['msg'] = $e->getMessage();
                
            }
            return $returnMsg;
        }
    }
    private function base64url_encode($data)
    {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }
}
?>