MinioService.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service;
  4. use Aws\S3\S3Client;
  5. use Hyperf\HttpServer\Contract\ResponseInterface;
  6. use function Hyperf\Support\env;
  7. use App\Tools\Result;
  8. use Hyperf\HttpMessage\Upload\UploadedFile;
  9. class MinioService
  10. {
  11. /**
  12. * @Inject
  13. * @var ResponseInterface
  14. */
  15. protected $response;
  16. /**
  17. * @Inject
  18. * @var \Hyperf\Config\ConfigInterface
  19. */
  20. protected $config;
  21. protected $s3Client;
  22. public function __construct()
  23. {
  24. $this->s3Client = new S3Client([
  25. 'version' => 'latest',
  26. 'region' => 'chinese',
  27. 'endpoint' => env("OSS_ENDPOINT"),
  28. 'use_path_style_endpoint' => true,
  29. 'credentials' => [
  30. 'key' => env("OSS_KEY"),
  31. 'secret' => env("OSS_SECRET"),
  32. ],
  33. ]);
  34. }
  35. /**
  36. * 没几把鸟用用来测试的
  37. * @return \Psr\Http\Message\ResponseInterface
  38. */
  39. public function listBuckets()
  40. {
  41. try {
  42. // 获取所有存储桶列表
  43. $result = $this->s3Client->listBuckets();
  44. // 提取存储桶名称
  45. $buckets = array_column($result['Buckets'], 'Name');
  46. return Result::success($buckets);
  47. } catch (\Aws\Exception\AwsException $e) {
  48. return Result::error("报错了");
  49. } catch (\Exception $e) {
  50. return Result::error("报错了");
  51. }
  52. }
  53. /**
  54. * 上传文件
  55. * @return array|string[]
  56. */
  57. public function uploadFile($data)
  58. {
  59. $acceptExt = ['png', 'jpg', 'jpeg', 'gif', 'xls', 'xlsx', 'pdf', 'doc', 'docx', 'ppt', 'zip', 'pptx', 'mp4', 'flv','rar','tar'];
  60. try {
  61. if (!in_array( $data['ext'], $acceptExt)) {
  62. return Result::error('文件名后缀不允许');
  63. }
  64. $fileName = time().mt_rand(1, 1000000) . '.' . $data['ext'];
  65. $finalPath = DIRECTORY_SEPARATOR.date('Ymd').DIRECTORY_SEPARATOR . $fileName;
  66. $key = $data['contentType'].$finalPath;
  67. var_dump("key:",$key);
  68. $result = $this->s3Client->putObject([
  69. 'Bucket' => env("BUCKET"),
  70. 'Key' => $key,
  71. 'Body' => base64_decode($data['fileContent']),
  72. 'ACL' => 'public-read',
  73. 'ContentType' => $data['contentType'],
  74. ]);
  75. $rep = [
  76. 'imgUrl'=>$result['ObjectURL'],
  77. 'id'=>uniqid(),
  78. 'src'=>$key,
  79. 'fileName'=>$fileName,
  80. 'fileType'=> $data['ext'],
  81. 'oldFileName'=>$data['fileName']
  82. ];
  83. return Result::success($rep);
  84. } catch (\Exception $e) {
  85. return Result::error($e->getMessage());
  86. }
  87. }
  88. }