Qcloud.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace app\common\library\storage\engine;
  3. use Qcloud\Cos\Client;
  4. /**
  5. * 腾讯云存储引擎 (COS)
  6. * Class Qiniu
  7. * @package app\common\library\storage\engine
  8. */
  9. class Qcloud extends Server
  10. {
  11. private $config;
  12. private $cosClient;
  13. /**
  14. * 构造方法
  15. * Qcloud constructor.
  16. * @param $config
  17. */
  18. public function __construct($config)
  19. {
  20. parent::__construct();
  21. $this->config = $config;
  22. // 创建COS控制类
  23. $this->createCosClient();
  24. }
  25. /**
  26. * 创建COS控制类
  27. */
  28. private function createCosClient()
  29. {
  30. $this->cosClient = new Client([
  31. 'region' => $this->config['region'],
  32. 'credentials' => [
  33. 'secretId' => $this->config['secret_id'],
  34. 'secretKey' => $this->config['secret_key'],
  35. ],
  36. ]);
  37. }
  38. /**
  39. * 执行上传
  40. * @return bool|mixed
  41. */
  42. public function upload()
  43. {
  44. // 上传文件
  45. // putObject(上传接口,最大支持上传5G文件)
  46. try {
  47. $result = $this->cosClient->putObject([
  48. 'Bucket' => $this->config['bucket'],
  49. 'Key' => $this->fileName,
  50. 'Body' => fopen($this->getRealPath(), 'rb')
  51. ]);
  52. return true;
  53. } catch (\Exception $e) {
  54. $this->error = $e->getMessage();
  55. return false;
  56. }
  57. }
  58. /**
  59. * 删除文件
  60. * @param $fileName
  61. * @return bool|mixed
  62. */
  63. public function delete($fileName)
  64. {
  65. try {
  66. $result = $this->cosClient->deleteObject(array(
  67. 'Bucket' => $this->config['bucket'],
  68. 'Key' => $fileName
  69. ));
  70. return true;
  71. } catch (\Exception $e) {
  72. $this->error = $e->getMessage();
  73. return false;
  74. }
  75. }
  76. /**
  77. * 返回文件路径
  78. * @return mixed
  79. */
  80. public function getFileName()
  81. {
  82. return $this->fileName;
  83. }
  84. }