QcloudTarget.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2018-01-16 14:46
  7. */
  8. namespace feehi\cdn;
  9. use Qcloud\Cos\Client;
  10. use Exception;
  11. class QcloudTarget extends TargetAbstract implements TargetInterface
  12. {
  13. public $region;
  14. public $appId;
  15. public $secretId;
  16. public $secretKey;
  17. public $bucket;
  18. /** @var Client */
  19. protected $client;
  20. public function init()
  21. {
  22. parent::init();
  23. if( empty($this->region) ) throw new Exception("Qcloud region cannot be blank");
  24. if( empty($this->appId) ) throw new Exception("Qcloud appId cannot be blank");
  25. if( empty($this->secretId) ) throw new Exception("Qcloud secretId cannot be blank");
  26. if( empty($this->secretKey) ) throw new Exception("Qcloud secretKey cannot be blank");
  27. $this->client = new Client([
  28. 'region' => $this->region,
  29. 'credentials'=> [
  30. 'secretId' => $this->secretId,
  31. 'secretKey' => $this->secretKey
  32. ]
  33. ]);
  34. }
  35. public function upload($localFile, $destFile)
  36. {
  37. try {
  38. $result = $this->client->upload(
  39. $bucket = $this->getWholeBucketName(),
  40. $key = $destFile,
  41. $body = fopen($localFile,'r+')
  42. );
  43. return true;
  44. } catch (\Exception $e) {
  45. $this->lastError = $e->getMessage();
  46. return false;
  47. }
  48. }
  49. public function multiUpload($localFile, $destFile)
  50. {
  51. try {
  52. $result = $this->client->upload(
  53. $bucket = $this->getWholeBucketName(),
  54. $key = $destFile,
  55. $body = fopen($localFile, 'rb'),
  56. $options = array(
  57. "ACL"=>'private',
  58. 'CacheControl' => 'private'));
  59. return true;
  60. } catch (\Exception $e) {
  61. $this->lastError = $e->getMessage();
  62. return false;
  63. }
  64. }
  65. public function exists($destFile)
  66. {
  67. try {
  68. $result = $this->client->headObject(array('Bucket' => $this->getWholeBucketName(), 'Key' => $destFile));
  69. return true;
  70. }catch (Exception $e){
  71. return false;
  72. }
  73. }
  74. public function delete($destFile)
  75. {
  76. try {
  77. $result = $this->client->deleteObject([
  78. 'Bucket' => $this->getWholeBucketName(),
  79. 'Key' => $destFile
  80. ]
  81. );
  82. return true;
  83. }catch (Exception $e){
  84. $this->lastError = $e->getMessage();
  85. return false;
  86. }
  87. }
  88. private function getWholeBucketName()
  89. {
  90. //bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
  91. return $this->bucket . '-' . $this->appId;
  92. }
  93. }