S3.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace app\common\extend\upload;
  3. use Aws\S3\S3Client;
  4. use Aws\Exception\AwsException;
  5. class S3
  6. {
  7. public $name = 'S3';
  8. public $ver = '1.0';
  9. private $config = [];
  10. public function __construct($config = []) {
  11. $this->config = $config;
  12. }
  13. public function submit($file_path)
  14. {
  15. $bucket = $GLOBALS['config']['upload']['api']['s3']['bucket'];
  16. $accessKey = $GLOBALS['config']['upload']['api']['s3']['accesskey'];
  17. $secretKey = $GLOBALS['config']['upload']['api']['s3']['secretkey'];
  18. $region = $GLOBALS['config']['upload']['api']['s3']['region'];
  19. $endpoint = !empty($GLOBALS['config']['upload']['api']['s3']['endpoint']) ? $GLOBALS['config']['upload']['api']['s3']['endpoint'] : '';
  20. $basepath = !empty($GLOBALS['config']['upload']['api']['s3']['basepath']) ? $GLOBALS['config']['upload']['api']['s3']['basepath'] : '';
  21. $domain = !empty($GLOBALS['config']['upload']['api']['s3']['domain']) ? $GLOBALS['config']['upload']['api']['s3']['domain'] : '';
  22. require_once ROOT_PATH . 'extend/aws/autoload.php';
  23. $options = [
  24. 'region' => $region,
  25. 'version' => '2006-03-01',
  26. 'credentials' => [
  27. 'key' => $accessKey,
  28. 'secret' => $secretKey
  29. ]
  30. ];
  31. if (!empty($endpoint)) {
  32. $options['endpoint'] = $endpoint;
  33. $options['use_path_style_endpoint'] = true;
  34. }
  35. $s3 = new S3Client($options);
  36. try {
  37. $filePath = ROOT_PATH . $file_path;
  38. $key = !empty($basepath) ? rtrim($basepath, '/') . '/' . ltrim($file_path, '/') : $file_path;
  39. $result = $s3->putObject([
  40. 'Bucket' => $bucket,
  41. 'Key' => $key,
  42. 'Body' => fopen($filePath, 'r'),
  43. 'ACL' => 'public-read'
  44. ]);
  45. } catch (AwsException $e) {
  46. echo $e->getMessage() . "\n";
  47. }
  48. empty($this->config['keep_local']) && @unlink($filePath);
  49. if (!empty($domain)) {
  50. return rtrim($domain, '/') . '/' . $bucket . '/' . $key;
  51. }
  52. return $result['ObjectURL'];
  53. }
  54. }