Oss.php 6.5 KB

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