MinioService.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. var_dump($e->getMessage());
  49. return Result::error("报错了");
  50. } catch (\Exception $e) {
  51. var_dump($e->getMessage());
  52. return Result::error("报错了");
  53. }
  54. }
  55. /**
  56. * 上传文件
  57. * @return array|string[]
  58. */
  59. public function uploadFile($data)
  60. {
  61. $acceptExt = ['png', 'jpg', 'jpeg', 'gif', 'xls', 'xlsx', 'pdf', 'doc', 'docx', 'ppt', 'zip', 'pptx', 'mp4', 'flv','rar','tar'];
  62. try {
  63. if (!in_array( $data['ext'], $acceptExt)) {
  64. return Result::error('文件名后缀不允许');
  65. }
  66. $fileName = time().mt_rand(1, 1000000) . '.' . $data['ext'];
  67. $finalPath = DIRECTORY_SEPARATOR.date('Ymd').DIRECTORY_SEPARATOR . $fileName;
  68. $key = $data['contentType'].$finalPath;
  69. var_dump("===key:",$key);
  70. $result = $this->s3Client->putObject([
  71. 'Bucket' => env("BUCKET"),
  72. 'Key' => $key,
  73. 'Body' => base64_decode($data['fileContent']),
  74. 'ACL' => 'public-read',
  75. 'ContentType' => $data['contentType'],
  76. ]);
  77. var_dump("返回值:",$result);
  78. $rep = [
  79. 'imgUrl'=>$result['ObjectURL'],
  80. 'id'=>uniqid(),
  81. 'src'=>$key,
  82. 'fileName'=>$fileName,
  83. 'fileType'=> $data['ext'],
  84. 'oldFileName'=>$data['fileName'],
  85. 'oldName'=>substr($data['fileName'], 0, -(strlen($data['ext'])+1)),
  86. ];
  87. return Result::success($rep);
  88. } catch (\Exception $e) {
  89. return Result::error($e->getMessage());
  90. }
  91. }
  92. }