Oss.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. <?php
  2. namespace crmeb\services\upload\storage;
  3. use crmeb\basic\BaseUpload;
  4. use crmeb\exceptions\UploadException;
  5. use Guzzle\Http\EntityBody;
  6. use OSS\Core\OssException;
  7. use OSS\OssClient;
  8. use think\exception\ValidateException;
  9. /**
  10. * 阿里云OSS上传
  11. * Class OSS
  12. */
  13. class Oss extends BaseUpload
  14. {
  15. /**
  16. * accessKey
  17. * @var mixed
  18. */
  19. protected $accessKey;
  20. /**
  21. * secretKey
  22. * @var mixed
  23. */
  24. protected $secretKey;
  25. /**
  26. * 句柄
  27. * @var \OSS\OssClient
  28. */
  29. protected $handle;
  30. /**
  31. * 空间域名 Domain
  32. * @var mixed
  33. */
  34. protected $uploadUrl;
  35. /**
  36. * 存储空间名称 公开空间
  37. * @var mixed
  38. */
  39. protected $storageName;
  40. /**
  41. * COS使用 所属地域
  42. * @var mixed|null
  43. */
  44. protected $storageRegion;
  45. /**
  46. * 初始化
  47. * @param array $config
  48. * @return mixed|void
  49. */
  50. protected function initialize(array $config)
  51. {
  52. parent::initialize($config);
  53. $this->accessKey = $config['accessKey'] ?? null;
  54. $this->secretKey = $config['secretKey'] ?? null;
  55. $this->uploadUrl = $this->checkUploadUrl($config['uploadUrl'] ?? '');
  56. $this->storageName = $config['storageName'] ?? null;
  57. $this->storageRegion = $config['storageRegion'] ?? null;
  58. }
  59. /**
  60. * 初始化oss
  61. * @return OssClient
  62. * @throws OssException
  63. */
  64. protected function app()
  65. {
  66. if (!$this->accessKey || !$this->secretKey) {
  67. throw new UploadException('Please configure accessKey and secretKey');
  68. }
  69. $this->handle = new OssClient($this->accessKey, $this->secretKey, $this->storageRegion);
  70. if (!$this->handle->doesBucketExist($this->storageName)) {
  71. $this->handle->createBucket($this->storageName, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
  72. }
  73. return $this->handle;
  74. }
  75. /**
  76. * 上传文件
  77. * @param string $file
  78. * @return array|bool|mixed|\StdClass
  79. */
  80. public function move(string $file = 'file')
  81. {
  82. $fileHandle = app()->request->file($file);
  83. if (!$fileHandle) {
  84. return $this->setError('Upload file does not exist');
  85. }
  86. if ($this->validate) {
  87. try {
  88. validate([$file => $this->validate])->check([$file => $fileHandle]);
  89. } catch (ValidateException $e) {
  90. return $this->setError($e->getMessage());
  91. }
  92. }
  93. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  94. try {
  95. $uploadInfo = $this->app()->uploadFile($this->storageName, $key, $fileHandle->getRealPath());
  96. if (!isset($uploadInfo['info']['url'])) {
  97. return $this->setError('Upload failure');
  98. }
  99. $this->fileInfo->uploadInfo = $uploadInfo;
  100. $this->fileInfo->filePath = $this->uploadUrl .'/'. $key;
  101. $this->fileInfo->fileName = $key;
  102. return $this->fileInfo;
  103. } catch (UploadException $e) {
  104. return $this->setError($e->getMessage());
  105. }
  106. }
  107. /**
  108. * 文件流上传
  109. * @param string $fileContent
  110. * @param string|null $key
  111. * @return bool|mixed
  112. */
  113. public function stream(string $fileContent, string $key = null)
  114. {
  115. try {
  116. if (!$key) {
  117. $key = $this->saveFileName();
  118. }
  119. $fileContent = (string)EntityBody::factory($fileContent);
  120. $uploadInfo = $this->app()->putObject($this->storageName, $key, $fileContent);
  121. if (!isset($uploadInfo['info']['url'])) {
  122. return $this->setError('Upload failure');
  123. }
  124. $this->fileInfo->uploadInfo = $uploadInfo;
  125. $this->fileInfo->filePath = $this->uploadUrl .'/'. $key;
  126. $this->fileInfo->fileName = $key;
  127. return $this->fileInfo;
  128. } catch (UploadException $e) {
  129. return $this->setError($e->getMessage());
  130. }
  131. }
  132. /**
  133. * 删除资源
  134. * @param $key
  135. * @return mixed
  136. */
  137. public function delete(string $key)
  138. {
  139. try {
  140. return $this->app()->deleteObject($this->storageName, $key);
  141. } catch (OssException $e) {
  142. return $this->setError($e->getMessage());
  143. }
  144. }
  145. /**
  146. * 获取OSS上传密钥
  147. * @return mixed|void
  148. */
  149. public function getTempKeys($callbackUrl = '', $dir = '')
  150. {
  151. // TODO: Implement getTempKeys() method.
  152. $base64CallbackBody = base64_encode(json_encode([
  153. 'callbackUrl' => $callbackUrl,
  154. 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
  155. 'callbackBodyType' => "application/x-www-form-urlencoded"
  156. ]));
  157. $policy = json_encode([
  158. 'expiration' => $this->gmtIso8601(time() + 30),
  159. 'conditions' =>
  160. [
  161. [0 => 'content-length-range', 1 => 0, 2 => 1048576000],
  162. [0 => 'starts-with', 1 => '$key', 2 => $dir]
  163. ]
  164. ]);
  165. $base64Policy = base64_encode($policy);
  166. $signature = base64_encode(hash_hmac('sha1', $base64Policy, $this->secretKey, true));
  167. return [
  168. 'accessid' => $this->accessKey,
  169. 'host' => $this->uploadUrl,
  170. 'policy' => $base64Policy,
  171. 'signature' => $signature,
  172. 'expire' => time() + 30,
  173. 'callback' => $base64CallbackBody,
  174. 'type' => 'OSS'
  175. ];
  176. }
  177. /**
  178. * 获取ISO时间格式
  179. * @param $time
  180. * @return string
  181. */
  182. protected function gmtIso8601($time)
  183. {
  184. $dtStr = date("c", $time);
  185. $mydatetime = new \DateTime($dtStr);
  186. $expiration = $mydatetime->format(\DateTime::ISO8601);
  187. $pos = strpos($expiration, '+');
  188. $expiration = substr($expiration, 0, $pos);
  189. return $expiration . "Z";
  190. }
  191. }