Qcloud.php 2.6 KB

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