Qcloud.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\common\library\storage\engine;
  13. use Qcloud\Cos\Client;
  14. /**
  15. * 腾讯云存储引擎 (COS)
  16. * Class Qcloud
  17. * @package app\common\library\storage\engine
  18. */
  19. class Qcloud extends Basics
  20. {
  21. // Qcloud类
  22. private $cosClient;
  23. /**
  24. * 构造方法
  25. * Qcloud constructor.
  26. * @param string $storage 存储方式
  27. * @param array|null $config 存储配置
  28. */
  29. public function __construct(string $storage, array $config = null)
  30. {
  31. parent::__construct($storage, $config);
  32. // 创建Qcloud类
  33. $this->createCosClient();
  34. }
  35. /**
  36. * 创建COS控制类
  37. */
  38. private function createCosClient()
  39. {
  40. $this->cosClient = new Client([
  41. 'region' => $this->config['region'],
  42. 'credentials' => [
  43. 'secretId' => $this->config['secret_id'],
  44. 'secretKey' => $this->config['secret_key'],
  45. ],
  46. ]);
  47. }
  48. /**
  49. * 执行上传
  50. * @return bool|mixed
  51. */
  52. public function upload()
  53. {
  54. // 上传文件
  55. // putObject(上传接口,最大支持上传5G文件)
  56. try {
  57. $result = $this->cosClient->putObject([
  58. 'Bucket' => $this->config['bucket'],
  59. 'Key' => $this->getSaveFileInfo()['file_path'],
  60. 'Body' => fopen($this->getRealPath(), 'rb')
  61. ]);
  62. return true;
  63. } catch (\Exception $e) {
  64. $this->error = $e->getMessage();
  65. return false;
  66. }
  67. }
  68. /**
  69. * 删除文件
  70. * @param string $fileName
  71. * @return bool|mixed
  72. */
  73. public function delete(string $fileName)
  74. {
  75. try {
  76. $result = $this->cosClient->deleteObject(array(
  77. 'Bucket' => $this->config['bucket'],
  78. 'Key' => $fileName
  79. ));
  80. return true;
  81. } catch (\Exception $e) {
  82. $this->error = $e->getMessage();
  83. return false;
  84. }
  85. }
  86. }