CosV5Service.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: weifeng
  5. * Date: 2020-05-11
  6. * Time: 17:53
  7. *
  8. * .--, .--,
  9. * ( ( \.---./ ) )
  10. * '.__/o o\__.'
  11. * {= ^ =}
  12. * > - <
  13. * / \
  14. * // \\
  15. * //| . |\\
  16. * "'\ /'"_.-~^`'-.
  17. * \ _ /--' `
  18. * ___)( )(___
  19. * (((__) (__))) 梦之所想,心之所向.
  20. */
  21. namespace app\common\services;
  22. class CosV5Service
  23. {
  24. /**
  25. * 初始化
  26. * @param $region
  27. * @param $secretId
  28. * @param $secretKey
  29. * @return \Qcloud\Cos\Client
  30. */
  31. public static function init($region, $secretId, $secretKey)
  32. {
  33. return new \Qcloud\Cos\Client(
  34. array(
  35. 'region' => $region,
  36. 'schema' => 'https', //协议头部,默认为http
  37. 'credentials'=> array(
  38. 'secretId' => $secretId,
  39. 'secretKey' => $secretKey),
  40. ));
  41. }
  42. /**
  43. * 上传文件流
  44. * @param $bucket
  45. * @param $key
  46. * @param $srcPath
  47. * @param $cosClient
  48. */
  49. public static function uploadStream($bucket, $key, $file, $cosClient)
  50. {
  51. try {
  52. if ($file) {
  53. $result = $cosClient->putObject(array(
  54. 'Bucket' => $bucket,
  55. 'Key' => $key,
  56. 'Body' => file_get_contents($file),
  57. ));
  58. return $result;
  59. } else {
  60. return '文件资源不存在';
  61. }
  62. } catch (\Exception $e) {
  63. \Log::error('qcloud-cos上传文件流报错', $e->getMessage());
  64. return $e->getMessage();
  65. }
  66. }
  67. /**
  68. * 获取上传的url
  69. * @param $bucket
  70. * @param $key
  71. * @param $cosClient
  72. * @param $expire
  73. */
  74. public static function getObjUrl($bucket, $key, $cosClient, $expire)
  75. {
  76. try {
  77. $signedUrl = $cosClient->getObjectUrl($bucket, $key, '+'.$expire.' minutes');
  78. // 请求成功
  79. return $signedUrl;
  80. } catch (\Exception $e) {
  81. // 请求失败
  82. \Log::error('qcloud-cos读取文件报错', $e);
  83. return false;
  84. }
  85. }
  86. /**
  87. * 获取文件 UrL
  88. * @param $bucket
  89. * @param $key
  90. * @param $cosClient
  91. * @param $expire
  92. */
  93. public static function getObjectUrl($bucket, $key, $cosClient, $expire)
  94. {
  95. try {
  96. $signedUrl = $cosClient->getObjectUrl($bucket, $key, '+'.$expire.' minutes');
  97. // 请求成功
  98. return $signedUrl;
  99. } catch (\Exception $e) {
  100. // 请求失败
  101. \Log::error('qcloud-cos读取文件报错', $e);
  102. return false;
  103. }
  104. }
  105. }