AliyunOss.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. <?php
  2. namespace Api;
  3. use think\Config;
  4. use OSS\Model\RefererConfig;
  5. use service\SystemConfigService;
  6. /**
  7. * Class AliyunOss
  8. * @package Api
  9. */
  10. class AliyunOss extends AliyunSdk
  11. {
  12. /**
  13. * OSS存储桶名
  14. * @var string
  15. */
  16. protected $OssBucket;
  17. /**
  18. * OSS 地域节点
  19. * @var string
  20. */
  21. protected $OssEndpoint;
  22. /**
  23. * 外网访问地址
  24. * @var string
  25. */
  26. protected $uploadUrl;
  27. /**
  28. * 上传验证规则
  29. * @var string
  30. */
  31. protected $autoValidate;
  32. /**
  33. * 是否开启防盗链
  34. * @var array
  35. */
  36. protected $referer;
  37. /**
  38. * 初始化参数
  39. */
  40. protected function _initialize()
  41. {
  42. $this->OssEndpoint = isset($this->config['OssEndpoint']) ? $this->config['OssEndpoint'] : null;
  43. $this->OssBucket = isset($this->config['OssBucket']) ? $this->config['OssBucket'] : null;
  44. $this->uploadUrl = isset($this->config['uploadUrl']) ? $this->config['uploadUrl'] : null;
  45. $this->checkUploadUrl();
  46. $this->referer = isset($this->config['referer']) && is_array($this->config['referer']) ? $this->config['referer'] : [];
  47. }
  48. /**
  49. * 验证合法上传域名
  50. */
  51. protected function checkUploadUrl()
  52. {
  53. $site_url=SystemConfigService::get('site_url');
  54. $https = "/^https:[\/]{2}[a-z]+[.]{1}[a-z\d\-]+[.]{1}[a-z\d]*[\/]*[A-Za-z\d]*[\/]*[A-Za-z\d]*/";
  55. if ($this->uploadUrl) {
  56. if (preg_match($https, $site_url)) {
  57. if (strstr($this->uploadUrl, 'https') === false) {
  58. $this->uploadUrl = 'https://' . $this->uploadUrl;
  59. }
  60. }else{
  61. if (strstr($this->uploadUrl, 'http') === false) {
  62. $this->uploadUrl = 'http://' . $this->uploadUrl;
  63. }
  64. }
  65. }
  66. }
  67. /**
  68. * 初始化
  69. * @return null|\OSS\OssClient
  70. * @throws \OSS\Core\OssException
  71. */
  72. public function init()
  73. {
  74. if ($this->client === null) {
  75. $this->client = new \OSS\OssClient($this->AccessKey, $this->AccessKeySecret, $this->OssEndpoint);
  76. if (!$this->client->doesBucketExist($this->OssBucket)) {
  77. $this->client->createBucket($this->OssBucket, \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
  78. }
  79. if ($this->referer) {
  80. $refererConfig = new RefererConfig();
  81. // 设置允许空Referer。
  82. $refererConfig->setAllowEmptyReferer(true);
  83. foreach ($this->referer as $url) {
  84. $refererConfig->addReferer($url);
  85. }
  86. $this->client->putBucketReferer($this->OssBucket, $refererConfig);
  87. }
  88. }
  89. return $this->client;
  90. }
  91. /**
  92. * 设置防盗链
  93. * @param array $referer
  94. * @return $this
  95. */
  96. public function setReferer(array $referer = [])
  97. {
  98. $this->referer = $referer;
  99. return $this;
  100. }
  101. /**
  102. * 验证规则
  103. * @param array $autoValidate
  104. * @return $this
  105. */
  106. public function validate(array $autoValidate = [])
  107. {
  108. if (!$autoValidate) {
  109. $autoValidate = Config::get('upload.Validate');
  110. }
  111. $this->autoValidate = $autoValidate;
  112. return $this;
  113. }
  114. /**
  115. * 设置OSS存储桶名
  116. * @param string $OssBucket
  117. * @return $this
  118. * */
  119. public function setOssBucketAttr($OssBucket)
  120. {
  121. $this->OssBucket = $OssBucket;
  122. return $this;
  123. }
  124. /**
  125. * 设置OSS存储外网访问域名
  126. * @param string $OssEndpoint
  127. * @return $this
  128. * */
  129. public function setOssEndpointAttr($OssEndpoint)
  130. {
  131. $this->OssEndpoint = $OssEndpoint;
  132. return $this;
  133. }
  134. /**
  135. * 提取文件名
  136. * @param string $path
  137. * @param string $ext
  138. * @return string
  139. */
  140. protected function saveFileName($path = null, $ext = 'jpg')
  141. {
  142. return ($path ? substr(md5($path), 0, 5) : '') . date('YmdHis') . rand(0, 9999) . '.' . $ext;
  143. }
  144. /**
  145. * 获取文件后缀
  146. * @param \think\File $file
  147. * @return string
  148. */
  149. protected function getExtension(\think\File $file)
  150. {
  151. $pathinfo = pathinfo($file->getInfo('name'));
  152. return isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
  153. }
  154. /**
  155. * 上传图片
  156. * @param $fileName
  157. * @return bool
  158. */
  159. public function upload($fileName)
  160. {
  161. $fileHandle = request()->file($fileName);
  162. $key = $this->saveFileName($fileHandle->getRealPath(), $this->getExtension($fileHandle));
  163. try {
  164. if ($this->autoValidate) {
  165. $fileHandle->validate($this->autoValidate);
  166. $this->autoValidate = null;
  167. }
  168. $uploadInfo = $this->init()->uploadFile($this->OssBucket, $key, $fileHandle->getRealPath());
  169. if (!isset($uploadInfo['info']['url'])) {
  170. return self::setErrorInfo('Upload failure');
  171. }
  172. return [
  173. 'url' => $uploadInfo['info']['url'],
  174. 'key' => $key
  175. ];
  176. } catch (\Throwable $e) {
  177. return self::setErrorInfo($e);
  178. }
  179. }
  180. /**
  181. * 文件流上传
  182. * @param string $fileContent
  183. * @param string|null $key
  184. * @return bool|mixed
  185. */
  186. public function stream(string $fileContent, string $key = null)
  187. {
  188. try {
  189. if (!$key) {
  190. $key = $this->saveFileName();
  191. }
  192. $uploadInfo = $this->init()->putObject($this->OssBucket, $key, $fileContent);
  193. if (!isset($uploadInfo['info']['url'])) {
  194. return self::setErrorInfo('Upload failure');
  195. }
  196. return [
  197. 'url' => $uploadInfo['info']['url'],
  198. 'key' => $key
  199. ];
  200. } catch (Throwable $e) {
  201. return self::setErrorInfo($e);
  202. }
  203. }
  204. /**
  205. * 删除指定资源
  206. * @param 资源key
  207. * @return array
  208. * */
  209. public function delOssFile($key)
  210. {
  211. try {
  212. return $this->init()->deleteObject($this->OssBucket, $key);
  213. } catch (\Exception $e) {
  214. return self::setErrorInfo($e);
  215. }
  216. }
  217. /**
  218. * 获取签名
  219. * @param string $callbackUrl
  220. * @param string $dir
  221. * @return string
  222. */
  223. public function getSignature($callbackUrl = '', $dir = '')
  224. {
  225. $base64CallbackBody = base64_encode(json_encode([
  226. 'callbackUrl' => $callbackUrl,
  227. 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
  228. 'callbackBodyType' => "application/x-www-form-urlencoded"
  229. ]));
  230. $policy = json_encode([
  231. 'expiration' => $this->gmtIso8601(time() + 30),
  232. 'conditions' =>
  233. [
  234. [0 => 'content-length-range', 1 => 0, 2 => 1048576000],
  235. [0 => 'starts-with', 1 => '$key', 2 => $dir]
  236. ]
  237. ]);
  238. $base64Policy = base64_encode($policy);
  239. $signature = base64_encode(hash_hmac('sha1', $base64Policy, $this->AccessKeySecret, true));
  240. return [
  241. 'accessid' => $this->AccessKey,
  242. 'host' => $this->uploadUrl,
  243. 'policy' => $base64Policy,
  244. 'signature' => $signature,
  245. 'expire' => time() + 30,
  246. 'callback' => $base64CallbackBody
  247. ];
  248. }
  249. /**
  250. * 获取ISO时间格式
  251. * @param $time
  252. * @return string
  253. */
  254. protected function gmtIso8601($time)
  255. {
  256. $dtStr = date("c", $time);
  257. $mydatetime = new \DateTime($dtStr);
  258. $expiration = $mydatetime->format(\DateTime::ISO8601);
  259. $pos = strpos($expiration, '+');
  260. $expiration = substr($expiration, 0, $pos);
  261. return $expiration . "Z";
  262. }
  263. /**
  264. * 获取防盗链信息
  265. * @param string $bucket
  266. * @return RefererConfig
  267. * @throws \OSS\Core\OssException
  268. */
  269. public function getBucketReferer($bucket = '')
  270. {
  271. return $this->init()->getBucketReferer($bucket ? $bucket : $this->OssBucket);
  272. }
  273. /**
  274. * 清除防盗链
  275. * @param string $bucket
  276. * @return \OSS\Http\ResponseCore
  277. * @throws \OSS\Core\OssException
  278. */
  279. public function deleteBucketReferer($bucket = '')
  280. {
  281. $refererConfig = new RefererConfig();
  282. return $this->init()->putBucketReferer($bucket ? $bucket : $this->OssBucket, $refererConfig);
  283. }
  284. }