S3.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. require_once ROOT_PATH . 'extend/aws/autoload.php';
  20. $s3 = new S3Client([
  21. 'region' => $region,
  22. 'version' => '2006-03-01',
  23. 'credentials' => [
  24. 'key' => $accessKey,
  25. 'secret' => $secretKey
  26. ]
  27. ]);
  28. try {
  29. $filePath = ROOT_PATH . $file_path;
  30. $result = $s3->putObject([
  31. 'Bucket' => $bucket,
  32. 'Key' => $file_path,
  33. 'Body' => fopen($filePath, 'r'),
  34. 'ACL' => 'public-read'
  35. ]);
  36. } catch (AwsException $e) {
  37. echo $e->getMessage() . "\n";
  38. }
  39. empty($this->config['keep_local']) && @unlink($filePath);
  40. return $result['ObjectURL'];
  41. }
  42. }