basePath."/config/qcloud_".YII_ENV."_conf.php"); }else{ require_once(Yii::app()->basePath.'/..'."/protected/config/cache/qcloud.".YII_ENV.".php"); } class Qcloud{ private $cosClient; private $bucket; private $appId; private $secretId; //"云 API 密钥 SecretId"; private $secretKey; //"云 API 密钥 SecretKey"; private $timeOut; private $region; //设置一个默认的存储桶地域 public function __construct() { global $BUCKET; global $APPID; global $SECRETID; global $SECRETKEY; global $TIMEOUT; global $REGION ; $this->bucket=$BUCKET; $this->appId=$APPID; $this->secretId=$SECRETID; $this->secretKey=$SECRETKEY; $this->timeOut=$TIMEOUT; $this->region=$REGION; $this->cosClient = new Qcloud\Cos\Client( array( 'region' => $this->region, 'schema' => 'http', //协议头部,默认为http 'credentials'=> array( 'secretId' => $this->secretId , 'secretKey' => $this->secretKey, 'appId'=>$this->appId, 'timeout'=>$this->timeOut ) ) ); } public function putFile($key,$localFile){ $data=array( 'status'=>0 ); if(!file_exists($localFile)){ $data=array( 'msg'=>"文件不存在" ); //文件不存在 return $data; } if(!$body=fopen($localFile, 'rb')){ $data=array( 'msg'=>"文件拒绝访问" ); return $data; } try { $result = $this->cosClient->upload($this->bucket, $key, $body); if($result && isset($result['Location']) && $result['Location']){ $data['status']=1; $data['url']=$result['Location']; } } catch (\Exception $e) { // 请求失败 //echo($e); $data['msg']='上传失败'; } return $data; } //删除 key 就是url去掉前面的域名部分 public function deleteFile($key){ $object=array( 'Bucket'=>$this->bucket, 'Key'=>$key ); $result = array( 'status' => 0, 'msg' => '', 'data' => '', ); try { $result = $this->cosClient->deleteObject($object); // 请求成功 $result['status'] = 1; $result['data'] = ''; $result['msg'] = "delete $this->bucket/$key success"; } catch (\Exception $e) { // 请求失败 $result['msg'] = '删除失败'; } return $result; } }