OSSManager.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace App\Service;
  3. use Aws\S3\S3Client;
  4. use Hyperf\Contract\ConfigInterface;
  5. use Hyperf\Di\Annotation\Inject;
  6. class OSSManager
  7. {
  8. #[Inject]
  9. protected S3Client $s3Client;
  10. #[Inject]
  11. protected ConfigInterface $config;
  12. public function uploadFile($bucket, $key, $filePath)
  13. {
  14. $result = $this->s3Client->putObject([
  15. 'Bucket' => $bucket,
  16. 'Key' => $key,
  17. 'SourceFile' => $filePath,
  18. ]);
  19. return $result['ObjectURL']?? null;
  20. }
  21. public function downloadFile($bucket, $key, $downloadPath)
  22. {
  23. $result = $this->s3Client->getObject([
  24. 'Bucket' => $bucket,
  25. 'Key' => $key,
  26. ]);
  27. if ($result['ContentLength'] > 0) {
  28. file_put_contents($downloadPath, $result['Body']);
  29. }
  30. return true;
  31. }
  32. public function deleteFile($bucket, $key)
  33. {
  34. $this->s3Client->deleteObject([
  35. 'Bucket' => $bucket,
  36. 'Key' => $key,
  37. ]);
  38. return true;
  39. }
  40. }