OssService.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace app\common\service;
  3. use app\common\traits\ServiceTrait;
  4. use OSS\OssClient;
  5. use OSS\Core\OssException;
  6. use think\Exception;
  7. class OssService
  8. {
  9. use ServiceTrait;
  10. protected $ossClient;
  11. protected $bucket;
  12. protected $domain;
  13. public function __construct()
  14. {
  15. $config = config('common.oss');
  16. try {
  17. $this->ossClient = new OssClient(
  18. $config['access_key_id'],
  19. $config['access_key_secret'],
  20. $config['endpoint']
  21. );
  22. $this->bucket = $config['bucket'];
  23. $this->domain = $config['domain'];
  24. } catch (OssException $e) {
  25. throw new Exception('OSS初始化失败:' . $e->getMessage());
  26. }
  27. }
  28. /**
  29. * 上传文件
  30. * @param string $filePath 本地文件路径
  31. * @param string $object OSS存储路径
  32. * @return string 文件访问URL
  33. * @throws Exception
  34. */
  35. public function uploadFile($filePath, $object)
  36. {
  37. try {
  38. $result = $this->ossClient->uploadFile($this->bucket, $object, $filePath);
  39. if (!$result) {
  40. throw new Exception('文件上传失败');
  41. }
  42. return $result['oss-request-url'];
  43. } catch (OssException $e) {
  44. throw new Exception('文件上传失败:' . $e->getMessage());
  45. }
  46. }
  47. /**
  48. * 删除文件
  49. * @param string $object OSS存储路径
  50. * @return bool
  51. * @throws Exception
  52. */
  53. public function deleteFile($object)
  54. {
  55. try {
  56. $this->ossClient->deleteObject($this->bucket, $object);
  57. return true;
  58. } catch (OssException $e) {
  59. throw new Exception('文件删除失败:' . $e->getMessage());
  60. }
  61. }
  62. /**
  63. * 获取文件临时访问URL
  64. * @param string $object OSS存储路径
  65. * @param int $timeout 超时时间(秒)
  66. * @return string
  67. * @throws Exception
  68. */
  69. public function getSignedUrl($object, $timeout = 3600)
  70. {
  71. try {
  72. return $this->ossClient->signUrl($this->bucket, $object, $timeout);
  73. } catch (OssException $e) {
  74. throw new Exception('获取文件访问地址失败:' . $e->getMessage());
  75. }
  76. }
  77. }