Qcloud.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. require dirname(__FILE__) . '/qcloud/vendor/autoload.php';
  3. if(YII_ENV == 'development'){
  4. require_once(Yii::app()->basePath."/config/qcloud_".YII_ENV."_conf.php");
  5. }else{
  6. require_once(Yii::app()->basePath.'/..'."/protected/config/cache/qcloud.".YII_ENV.".php");
  7. }
  8. class Qcloud{
  9. private $cosClient;
  10. private $bucket;
  11. private $appId;
  12. private $secretId; //"云 API 密钥 SecretId";
  13. private $secretKey; //"云 API 密钥 SecretKey";
  14. private $timeOut;
  15. private $region; //设置一个默认的存储桶地域
  16. public function __construct()
  17. {
  18. global $BUCKET;
  19. global $APPID;
  20. global $SECRETID;
  21. global $SECRETKEY;
  22. global $TIMEOUT;
  23. global $REGION ;
  24. $this->bucket=$BUCKET;
  25. $this->appId=$APPID;
  26. $this->secretId=$SECRETID;
  27. $this->secretKey=$SECRETKEY;
  28. $this->timeOut=$TIMEOUT;
  29. $this->region=$REGION;
  30. $this->cosClient = new Qcloud\Cos\Client(
  31. array(
  32. 'region' => $this->region,
  33. 'schema' => 'http', //协议头部,默认为http
  34. 'credentials'=> array(
  35. 'secretId' => $this->secretId ,
  36. 'secretKey' => $this->secretKey,
  37. 'appId'=>$this->appId,
  38. 'timeout'=>$this->timeOut
  39. )
  40. )
  41. );
  42. }
  43. public function putFile($key,$localFile){
  44. $data=array(
  45. 'status'=>0
  46. );
  47. if(!file_exists($localFile)){
  48. $data=array(
  49. 'msg'=>"文件不存在"
  50. ); //文件不存在
  51. return $data;
  52. }
  53. if(!$body=fopen($localFile, 'rb')){
  54. $data=array(
  55. 'msg'=>"文件拒绝访问"
  56. );
  57. return $data;
  58. }
  59. try {
  60. $result = $this->cosClient->upload($this->bucket, $key, $body);
  61. if($result && isset($result['Location']) && $result['Location']){
  62. $data['status']=1;
  63. $data['url']=$result['Location'];
  64. }
  65. } catch (\Exception $e) {
  66. // 请求失败
  67. //echo($e);
  68. $data['msg']='上传失败';
  69. }
  70. return $data;
  71. }
  72. //删除 key 就是url去掉前面的域名部分
  73. public function deleteFile($key){
  74. $object=array(
  75. 'Bucket'=>$this->bucket,
  76. 'Key'=>$key
  77. );
  78. $result = array(
  79. 'status' => 0,
  80. 'msg' => '',
  81. 'data' => '',
  82. );
  83. try {
  84. $result = $this->cosClient->deleteObject($object);
  85. // 请求成功
  86. $result['status'] = 1;
  87. $result['data'] = '';
  88. $result['msg'] = "delete $this->bucket/$key success";
  89. } catch (\Exception $e) {
  90. // 请求失败
  91. $result['msg'] = '删除失败';
  92. }
  93. return $result;
  94. }
  95. }