Qcloud.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. // 使用curl获取$url
  70. $ch = curl_init();
  71. curl_setopt($ch, CURLOPT_URL, $url);
  72. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  73. curl_setopt($ch, CURLOPT_HEADER, 0);
  74. $content = curl_exec($ch);
  75. curl_close($ch);
  76. $this->cosClient->putObject([
  77. 'Bucket' => $this->config['bucket'],
  78. 'Key' => $key,
  79. 'Body' => $content,
  80. ]);
  81. return true;
  82. } catch (Exception $e) {
  83. $this->error = $e->getMessage();
  84. return false;
  85. }
  86. }
  87. /**
  88. * 删除文件
  89. * @param $fileName
  90. * @return bool|mixed
  91. */
  92. public function delete($fileName)
  93. {
  94. try {
  95. $this->cosClient->deleteObject(array(
  96. 'Bucket' => $this->config['bucket'],
  97. 'Key' => $fileName
  98. ));
  99. return true;
  100. } catch (Exception $e) {
  101. $this->error = $e->getMessage();
  102. return false;
  103. }
  104. }
  105. /**
  106. * 返回文件路径
  107. * @return mixed
  108. */
  109. public function getFileName()
  110. {
  111. return $this->fileName;
  112. }
  113. }