OssUpload.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace App\Service\Util\Support\Upload;
  3. class OssUpload
  4. {
  5. /**
  6. * @var string
  7. */
  8. protected string $dir = 'upload/';
  9. /**
  10. * @var int
  11. */
  12. protected int $expire = 30;
  13. protected string $accessKeyId;
  14. protected string $accessKeySecret;
  15. protected string $endpoint;
  16. protected int $maxSize;
  17. protected string $bucket;
  18. public function __construct()
  19. {
  20. $this->accessKeySecret = config('common.upload.oss.access_secret');
  21. $this->accessKeyId = config('common.upload.oss.access_id');
  22. $this->dir = date('Y-m-d') . '/';
  23. $this->endpoint = config('common.upload.oss.endpoint');
  24. $this->maxSize = config('common.upload.max_size');
  25. $this->bucket = config('common.upload.oss.bucket');
  26. }
  27. /**
  28. * config
  29. *
  30. * @return array
  31. */
  32. public function config(): array
  33. {
  34. return [
  35. 'bucket' => $this->bucket,
  36. 'accessKeyId' => $this->accessKeyId,
  37. 'host' => sprintf('https://%s.%s', $this->bucket, $this->endpoint),
  38. 'policy' => $this->policy(),
  39. 'signature' => $this->signature(),
  40. 'expire' => $this->getExpiration(),
  41. 'dir' => $this->dir,
  42. 'url' => $this->endpoint . $this->dir
  43. ];
  44. }
  45. /**
  46. *
  47. * @return string
  48. */
  49. protected function policy(): string
  50. {
  51. return base64_encode(json_encode([
  52. 'expiration' => $this->getExpiration(),
  53. 'conditions' => [
  54. ['starts-with', '$key', $this->dir],
  55. ['content-length-range', 0, $this->maxSize]
  56. ]
  57. ]));
  58. }
  59. /**
  60. *
  61. * @return string
  62. */
  63. protected function signature(): string
  64. {
  65. return base64_encode(
  66. \hash_hmac('sha1', $this->policy(), $this->accessKeySecret, true)
  67. );
  68. }
  69. /**
  70. *
  71. * @return string
  72. */
  73. protected function getExpiration(): string
  74. {
  75. return date('Y-m-d\TH:i:s\Z', time() + $this->expire);
  76. }
  77. }