Oss.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. * @param string $path
  79. * @return array|bool|mixed|\StdClass
  80. */
  81. public function move(string $file = 'file',$path = null)
  82. {
  83. $fileHandle = app()->request->file($file);
  84. if (!$fileHandle) {
  85. return $this->setError('Upload file does not exist');
  86. }
  87. if ($this->validate) {
  88. try {
  89. validate([$file => $this->validate])->check([$file => $fileHandle]);
  90. } catch (ValidateException $e) {
  91. return $this->setError($e->getMessage());
  92. }
  93. }
  94. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  95. if($path != null){
  96. $key = $path.$key;
  97. }
  98. try {
  99. $uploadInfo = $this->app()->uploadFile($this->storageName, $key, $fileHandle->getRealPath());
  100. if (!isset($uploadInfo['info']['url'])) {
  101. return $this->setError('Upload failure');
  102. }
  103. $this->fileInfo->uploadInfo = $uploadInfo;
  104. $this->fileInfo->filePath = $this->uploadUrl .'/'. $key;
  105. $this->fileInfo->fileName = $key;
  106. return $this->fileInfo;
  107. } catch (UploadException $e) {
  108. return $this->setError($e->getMessage());
  109. }
  110. }
  111. /**
  112. * 文件流上传
  113. * @param string $fileContent
  114. * @param string|null $key
  115. * @return bool|mixed
  116. */
  117. public function stream(string $fileContent, string $key = null)
  118. {
  119. try {
  120. if (!$key) {
  121. $key = $this->saveFileName();
  122. }
  123. $fileContent = (string)EntityBody::factory($fileContent);
  124. $uploadInfo = $this->app()->putObject($this->storageName, $key, $fileContent);
  125. if (!isset($uploadInfo['info']['url'])) {
  126. return $this->setError('Upload failure');
  127. }
  128. $this->fileInfo->uploadInfo = $uploadInfo;
  129. $this->fileInfo->filePath = $this->uploadUrl .'/'. $key;
  130. $this->fileInfo->fileName = $key;
  131. return $this->fileInfo;
  132. } catch (UploadException $e) {
  133. return $this->setError($e->getMessage());
  134. }
  135. }
  136. /**
  137. * 删除资源
  138. * @param $key
  139. * @return mixed
  140. */
  141. public function delete(string $key)
  142. {
  143. try {
  144. return $this->app()->deleteObject($this->storageName, $key);
  145. } catch (OssException $e) {
  146. return $this->setError($e->getMessage());
  147. }
  148. }
  149. /**
  150. * 获取OSS上传密钥
  151. * @return mixed|void
  152. */
  153. public function getTempKeys($callbackUrl = '', $dir = '')
  154. {
  155. // TODO: Implement getTempKeys() method.
  156. $base64CallbackBody = base64_encode(json_encode([
  157. 'callbackUrl' => $callbackUrl,
  158. 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
  159. 'callbackBodyType' => "application/x-www-form-urlencoded"
  160. ]));
  161. $policy = json_encode([
  162. 'expiration' => $this->gmtIso8601(time() + 30),
  163. 'conditions' =>
  164. [
  165. [0 => 'content-length-range', 1 => 0, 2 => 1048576000],
  166. [0 => 'starts-with', 1 => '$key', 2 => $dir]
  167. ]
  168. ]);
  169. $base64Policy = base64_encode($policy);
  170. $signature = base64_encode(hash_hmac('sha1', $base64Policy, $this->secretKey, true));
  171. return [
  172. 'accessid' => $this->accessKey,
  173. 'host' => $this->uploadUrl,
  174. 'policy' => $base64Policy,
  175. 'signature' => $signature,
  176. 'expire' => time() + 30,
  177. 'callback' => $base64CallbackBody,
  178. 'type' => 'OSS'
  179. ];
  180. }
  181. /**
  182. * 获取ISO时间格式
  183. * @param $time
  184. * @return string
  185. */
  186. protected function gmtIso8601($time)
  187. {
  188. $dtStr = date("c", $time);
  189. $mydatetime = new \DateTime($dtStr);
  190. $expiration = $mydatetime->format(\DateTime::ISO8601);
  191. $pos = strpos($expiration, '+');
  192. $expiration = substr($expiration, 0, $pos);
  193. return $expiration . "Z";
  194. }
  195. }