MinioService.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service;
  4. use Aws\S3\S3Client;
  5. use Hyperf\Di\Annotation\Inject;
  6. use Hyperf\HttpServer\Annotation\Controller;
  7. use Hyperf\HttpServer\Annotation\RequestMapping;
  8. use Hyperf\HttpServer\Contract\ResponseInterface;
  9. use function Hyperf\Support\env;
  10. class MinioService
  11. {
  12. /**
  13. * @Inject
  14. * @var ResponseInterface
  15. */
  16. protected $response;
  17. public function listBuckets()
  18. {
  19. // MinIO 配置
  20. $config = [
  21. 'version' => 'latest',
  22. 'region' => 'us-east-1', // 对于MinIO,这个参数通常不重要,但SDK可能需要它
  23. 'endpoint' => env("ENDPOINT"), // 替换为您的MinIO服务器地址
  24. 'use_path_style_endpoint' => true, // 对于MinIO,通常需要将此设置为true
  25. 'credentials' => [
  26. 'key' => 'Kr2gB8Lo3nRvm39naO43',
  27. 'secret' => '2cPcnAOs3YKiLEMonx62uRN3Ep4u1HYPeSNv1HzG',
  28. ],
  29. ];
  30. var_dump("配置信息:",$config);
  31. // 创建 MinIO 客户端
  32. $minioClient = new S3Client($config);
  33. // var_dump("连接:",$minioClient);
  34. try {
  35. // 获取所有存储桶列表
  36. $result = $minioClient->listBuckets();
  37. var_dump($result);
  38. // 提取存储桶名称
  39. $buckets = array_column($result['Buckets'], 'Name');
  40. // 返回响应
  41. return $this->response->json([
  42. 'success' => true,
  43. 'buckets' => $buckets,
  44. ]);
  45. } catch (\Aws\Exception\AwsException $e) {
  46. var_dump("错误:",$e->getMessage());
  47. // 处理AWS异常
  48. return $this->response->withStatus(500)->json([
  49. 'success' => false,
  50. 'error' => $e->getMessage(),
  51. ]);
  52. } catch (\Exception $e) {
  53. // 处理其他异常
  54. return $this->response->withStatus(500)->json([
  55. 'success' => false,
  56. 'error' => 'An unexpected error occurred: ' . $e->getMessage(),
  57. ]);
  58. }
  59. }
  60. }