FileService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Think.Admin
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://think.ctolog.com
  8. // +----------------------------------------------------------------------
  9. // | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
  10. // +----------------------------------------------------------------------
  11. // | github开源项目:https://github.com/zoujingli/Think.Admin
  12. // +----------------------------------------------------------------------
  13. namespace service;
  14. use Exception;
  15. use OSS\Core\OssException;
  16. use OSS\OssClient;
  17. use Qiniu\Auth;
  18. use Qiniu\Storage\BucketManager;
  19. use Qiniu\Storage\UploadManager;
  20. use think\Config;
  21. use think\Log;
  22. /**
  23. * 系统文件服务
  24. * Class FileService
  25. * @package service
  26. * @author Anyon <zoujingli@qq.com>
  27. * @date 2017/03/15 15:17
  28. */
  29. class FileService
  30. {
  31. /**
  32. * 根据文件后缀获取文件MINE
  33. * @param array $exts 文件后缀
  34. * @param array $mine 文件后缀MINE信息
  35. * @return string
  36. */
  37. public static function getFileMine($exts, $mine = [])
  38. {
  39. $mines = Config::get('mines');
  40. foreach (is_string($exts) ? explode(',', $exts) : $exts as $_e) {
  41. if (isset($mines[strtolower($_e)])) {
  42. $_exinfo = $mines[strtolower($_e)];
  43. $mine[] = is_array($_exinfo) ? join(',', $_exinfo) : $_exinfo;
  44. }
  45. }
  46. return join(',', $mine);
  47. }
  48. /**
  49. * 获取文件当前URL地址
  50. * @param string $filename
  51. * @param string|null $storage
  52. * @return bool|string
  53. */
  54. public static function getFileUrl($filename, $storage = null)
  55. {
  56. if (self::hasFile($filename, $storage) === false) {
  57. return false;
  58. }
  59. switch (empty($storage) ? sysconf('storage_type') : $storage) {
  60. case 'local':
  61. return self::getBaseUriLocal() . $filename;
  62. case 'qiniu':
  63. return self::getBaseUriQiniu() . $filename;
  64. case 'oss':
  65. return self::getBaseUriOss() . $filename;
  66. }
  67. return false;
  68. }
  69. /**
  70. * 根据配置获取到七牛云文件上传目标地址
  71. * @return string
  72. */
  73. public static function getUploadLocalUrl()
  74. {
  75. return url('@admin/plugs/upload');
  76. }
  77. /**
  78. * 根据配置获取到七牛云文件上传目标地址
  79. * @param bool $isClient
  80. * @return string
  81. */
  82. public static function getUploadQiniuUrl($isClient = true)
  83. {
  84. $region = sysconf('storage_qiniu_region');
  85. $isHttps = !!sysconf('storage_qiniu_is_https');
  86. switch ($region) {
  87. case '华东':
  88. if ($isHttps) {
  89. return $isClient ? 'https://upload.qbox.me' : 'https://up.qbox.me';
  90. }
  91. return $isClient ? 'http://upload.qiniu.com' : 'http://up.qiniu.com';
  92. case '华北':
  93. if ($isHttps) {
  94. return $isClient ? 'https://upload-z1.qbox.me' : 'https://up-z1.qbox.me';
  95. }
  96. return $isClient ? 'http://upload-z1.qiniu.com' : 'http://up-z1.qiniu.com';
  97. case '北美':
  98. if ($isHttps) {
  99. return $isClient ? 'https://upload-na0.qbox.me' : 'https://up-na0.qbox.me';
  100. }
  101. return $isClient ? 'http://upload-na0.qiniu.com' : 'http://up-na0.qiniu.com';
  102. case '华南':
  103. default:
  104. if ($isHttps) {
  105. return $isClient ? 'https://upload-z2.qbox.me' : 'https://up-z2.qbox.me';
  106. }
  107. return $isClient ? 'http://upload-z2.qiniu.com' : 'http://up-z2.qiniu.com';
  108. }
  109. }
  110. /**
  111. * 获取AliOSS上传地址
  112. * @return string
  113. */
  114. public static function getUploadOssUrl()
  115. {
  116. return (request()->isSsl() ? 'https' : 'http') . '://' . sysconf('storage_oss_domain');
  117. }
  118. /**
  119. * 获取服务器URL前缀
  120. * @return string
  121. */
  122. public static function getBaseUriLocal()
  123. {
  124. $request = request();
  125. $base = $request->root();
  126. $root = strpos($base, '.') ? ltrim(dirname($base), DS) : $base;
  127. if ('' != $root) {
  128. $root = '/' . ltrim($root, '/');
  129. }
  130. return ($request->isSsl() ? 'https' : 'http') . '://' . $request->host() . "{$root}/static/upload/";
  131. }
  132. /**
  133. * 获取七牛云URL前缀
  134. * @return string
  135. */
  136. public static function getBaseUriQiniu()
  137. {
  138. return (sysconf('storage_qiniu_is_https') ? 'https' : 'http') . '://' . sysconf('storage_qiniu_domain') . '/';
  139. }
  140. /**
  141. * 获取AliOss URL前缀
  142. * @return string
  143. */
  144. public static function getBaseUriOss()
  145. {
  146. return (sysconf('storage_oss_is_https') ? 'https' : 'http') . '://' . sysconf('storage_oss_domain') . '/';
  147. }
  148. /**
  149. * 获取文件相对名称
  150. * @param string $location 文件标识
  151. * @param string $ext 文件后缀
  152. * @param string $pre 文件前缀
  153. * @return string
  154. */
  155. public static function getFileName($location, $ext = '', $pre = '')
  156. {
  157. return $pre . join('/', str_split(md5($location), 16)) . '.' . $ext;
  158. }
  159. /**
  160. * 检查文件是否已经存在
  161. * @param string $filename
  162. * @param string|null $storage
  163. * @return bool
  164. */
  165. public static function hasFile($filename, $storage = null)
  166. {
  167. switch (empty($storage) ? sysconf('storage_type') : $storage) {
  168. case 'local':
  169. return file_exists(ROOT_PATH . 'static/upload/' . $filename);
  170. case 'qiniu':
  171. $auth = new Auth(sysconf('storage_qiniu_access_key'), sysconf('storage_qiniu_secret_key'));
  172. $bucketMgr = new BucketManager($auth);
  173. list($ret, $err) = $bucketMgr->stat(sysconf('storage_qiniu_bucket'), $filename);
  174. return $err === null;
  175. case 'oss':
  176. $ossClient = new OssClient(sysconf('storage_oss_keyid'), sysconf('storage_oss_secret'), self::getBaseUriOss(), true);
  177. return $ossClient->doesObjectExist(sysconf('storage_oss_bucket'), $filename);
  178. }
  179. return false;
  180. }
  181. /**
  182. * 根据Key读取文件内容
  183. * @param string $filename
  184. * @param string|null $storage
  185. * @return string|null
  186. */
  187. public static function readFile($filename, $storage = null)
  188. {
  189. switch (empty($storage) ? sysconf('storage_type') : $storage) {
  190. case 'local':
  191. $file = ROOT_PATH . 'static/upload/' . $filename;
  192. return file_exists($file) ? file_get_contents($file) : '';
  193. case 'qiniu':
  194. $auth = new Auth(sysconf('storage_qiniu_access_key'), sysconf('storage_qiniu_secret_key'));
  195. return file_get_contents($auth->privateDownloadUrl(self::getBaseUriQiniu() . $filename));
  196. case 'oss':
  197. $ossClient = new OssClient(sysconf('storage_oss_keyid'), sysconf('storage_oss_secret'), self::getBaseUriOss(), true);
  198. return $ossClient->getObject(sysconf('storage_oss_bucket'), $filename);
  199. }
  200. Log::error("通过{$storage}读取文件{$filename}的不存在!");
  201. return null;
  202. }
  203. /**
  204. * 根据当前配置存储文件
  205. * @param string $filename
  206. * @param string $content
  207. * @param string|null $file_storage
  208. * @return array|false
  209. */
  210. public static function save($filename, $content, $file_storage = null)
  211. {
  212. $type = empty($file_storage) ? sysconf('storage_type') : $file_storage;
  213. if (!method_exists(__CLASS__, $type)) {
  214. Log::error("保存存储失败,调用{$type}存储引擎不存在!");
  215. return false;
  216. }
  217. return self::$type($filename, $content);
  218. }
  219. /**
  220. * 文件储存在本地
  221. * @param string $filename
  222. * @param string $content
  223. * @return array|null
  224. */
  225. public static function local($filename, $content)
  226. {
  227. try {
  228. $filepath = ROOT_PATH . 'static/upload/' . $filename;
  229. !file_exists(dirname($filepath)) && mkdir(dirname($filepath), '0755', true);
  230. if (file_put_contents($filepath, $content)) {
  231. $url = pathinfo(request()->baseFile(true), PATHINFO_DIRNAME) . '/static/upload/' . $filename;
  232. return ['file' => $filepath, 'hash' => md5_file($filepath), 'key' => "static/upload/{$filename}", 'url' => $url];
  233. }
  234. } catch (Exception $err) {
  235. Log::error('本地文件存储失败, ' . var_export($err, true));
  236. }
  237. return null;
  238. }
  239. /**
  240. * 七牛云存储
  241. * @param string $filename
  242. * @param string $content
  243. * @return array|null
  244. */
  245. public static function qiniu($filename, $content)
  246. {
  247. $auth = new Auth(sysconf('storage_qiniu_access_key'), sysconf('storage_qiniu_secret_key'));
  248. $token = $auth->uploadToken(sysconf('storage_qiniu_bucket'));
  249. $uploadMgr = new UploadManager();
  250. list($result, $err) = $uploadMgr->put($token, $filename, $content);
  251. if ($err !== null) {
  252. Log::error('七牛云文件上传失败, ' . var_export($err, true));
  253. return null;
  254. }
  255. $result['file'] = $filename;
  256. $result['url'] = self::getBaseUriQiniu() . $filename;
  257. return $result;
  258. }
  259. /**
  260. * 阿里云OSS
  261. * @param string $filename
  262. * @param string $content
  263. * @return array|null
  264. */
  265. public static function oss($filename, $content)
  266. {
  267. try {
  268. $ossClient = new OssClient(sysconf('storage_oss_keyid'), sysconf('storage_oss_secret'), self::getBaseUriOss(), true);
  269. $result = $ossClient->putObject(sysconf('storage_oss_bucket'), $filename, $content);
  270. return ['file' => $filename, 'hash' => $result['content-md5'], 'key' => $filename, 'url' => $result['oss-request-url']];
  271. } catch (OssException $err) {
  272. Log::error('阿里云OSS文件上传失败, ' . var_export($err, true));
  273. return null;
  274. }
  275. }
  276. /**
  277. * 下载文件到本地
  278. * @param string $url 文件URL地址
  279. * @param bool $isForce 是否强制重新下载文件
  280. * @return array|null;
  281. */
  282. public static function download($url, $isForce = false)
  283. {
  284. try {
  285. $filename = self::getFileName($url, strtolower(pathinfo($url, 4)), 'download/');
  286. if (false === $isForce && ($siteUrl = self::getFileUrl($filename, 'local'))) {
  287. $realfile = ROOT_PATH . 'static/upload/' . $filename;
  288. return ['file' => $realfile, 'hash' => md5_file($realfile), 'key' => "static/upload/{$filename}", 'url' => $siteUrl];
  289. }
  290. return self::local($filename, file_get_contents($url));
  291. } catch (\Exception $e) {
  292. Log::error("FileService 文件下载失败 [ {$url} ] . {$e->getMessage()}");
  293. return null;
  294. }
  295. }
  296. }