Qcloud.php 2.1 KB

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