记腾讯云 cos上传图片类

自己封装:

<?php
namespace CosUpload;
use Qcloud\Cos\Client;


class CosUpload
{
    //上传图片压缩包
    public static function sendzipimg($imgurl,$codeName,$isdel=0){
        return self::sendimg($imgurl,$codeName,'zipimg',$isdel);
    }
    
    /**
     * 腾讯对象存储-文件上传
     * @datatime 2018/05/17 09:20
     * @author lgp
     */
    public function goodsCosUp($tmpImg,$fileName,$path='goods_pic/'){
        
        $date = date('Y-m-d');
        $path = $path.$date.'/';
        $cosClient = new Client(array('region' =>config('app.cos.region'),'credentials'=> array('secretId' =>config('app.cos.secretId'),'secretKey' =>config('app.cos.secretKey'))));
        
        try {
            $result = $cosClient->putObject(array(
                'Bucket' => config('app.cos.bucket'),
                'Key' => $path.$fileName,
                'Body' => fopen($tmpImg, 'rb')));
        } catch (\Exception $e) {
           return false;
        }

        return     $result['Location'];

    }     
    
    public function otherCosUp($tmpImg,$fileName,$path='banner_pic/'){

        $path = $path.'/';
        $cosClient = new Client(array('region' =>config('app.cos.region'),'credentials'=> array('secretId' =>config('app.cos.secretId'),'secretKey' =>config('app.cos.secretKey'))));
        
        try {
            $result = $cosClient->putObject(array(
                'Bucket' => config('app.cos.bucket'),
                'Key' => $path.$fileName,
                'Body' => fopen($tmpImg, 'rb')));
        } catch (\Exception $e) {
           return false;
        }

        return     $result['Location'];

    }      
    
    
    public static  function delimg($url){
        
        $cosClient = new Client(array('region' =>config('app.cos.region'),'credentials'=> array('secretId' =>config('app.cos.secretId'),'secretKey' =>config('app.cos.secretKey'))));
        $Key=str_replace(config('app.cos.host'),'',$url);

        try {
            $result = $cosClient->deleteObject(array(
               'Bucket' =>  config('app.cos.bucket'),
               'Key' => $Key,
            //   'VersionId' => 'string'
            ));            
        } catch (\Exception $e) {

           return false;
        }

        return true;
    }    
    
    //下载文件到本地
    public static function downLoad($url,$downPath){
        
        $cosClient = new Client(array('region' =>config('app.cos.region'),'credentials'=> array('secretId' =>config('app.cos.secretId'),'secretKey' =>config('app.cos.secretKey'))));
        
        $Key=str_replace(config('app.cos.host'),'',$url);      
        try {
          $result = $cosClient->getObject(array(
              'Bucket' => config('app.cos.bucket'),
              'Key' => $Key,
              'SaveAs' => $downPath
          )); 
          // 请求成功
        } catch (\Exception $e) {
          
           return false;
        }   
        
          return true;
    }

}

 

posted @ 2021-06-15 15:12  Liiu  阅读(205)  评论(0编辑  收藏  举报