Upload.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkAdmin
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2014~2021 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: https://thinkadmin.top
  8. // +----------------------------------------------------------------------
  9. // | 开源协议 ( https://mit-license.org )
  10. // | 免费声明 ( https://thinkadmin.top/disclaimer )
  11. // +----------------------------------------------------------------------
  12. // | gitee 代码仓库:https://gitee.com/zoujingli/ThinkAdmin
  13. // | github 代码仓库:https://github.com/zoujingli/ThinkAdmin
  14. // +----------------------------------------------------------------------
  15. namespace app\admin\controller\api;
  16. use think\admin\Controller;
  17. use think\admin\Storage;
  18. use think\admin\storage\AliossStorage;
  19. use think\admin\storage\LocalStorage;
  20. use think\admin\storage\QiniuStorage;
  21. use think\admin\storage\TxcosStorage;
  22. use think\exception\HttpResponseException;
  23. use think\file\UploadedFile;
  24. use think\Response;
  25. /**
  26. * 文件上传接口
  27. * Class Upload
  28. * @package app\admin\controller\api
  29. */
  30. class Upload extends Controller
  31. {
  32. /**
  33. * 文件上传脚本
  34. * @return Response
  35. * @throws \think\db\exception\DataNotFoundException
  36. * @throws \think\db\exception\DbException
  37. * @throws \think\db\exception\ModelNotFoundException
  38. */
  39. public function index(): Response
  40. {
  41. $data = ['exts' => []];
  42. foreach (str2arr(sysconf('storage.allow_exts')) as $ext) {
  43. $data['exts'][$ext] = Storage::mime($ext);
  44. }
  45. $template = realpath(__DIR__ . '/../../view/api/upload.js');
  46. $data['exts'] = json_encode($data['exts'], JSON_UNESCAPED_UNICODE);
  47. return view($template, $data)->contentType('application/x-javascript');
  48. }
  49. /**
  50. * 文件上传检查
  51. * @login true
  52. * @throws \think\admin\Exception
  53. * @throws \think\db\exception\DataNotFoundException
  54. * @throws \think\db\exception\DbException
  55. * @throws \think\db\exception\ModelNotFoundException
  56. */
  57. public function state()
  58. {
  59. [$name, $safe] = [input('name'), $this->getSafe()];
  60. $data = ['uptype' => $this->getType(), 'safe' => intval($safe), 'key' => input('key')];
  61. if ($info = Storage::instance($data['uptype'])->info($data['key'], $safe, $name)) {
  62. $data['url'] = $info['url'];
  63. $data['key'] = $info['key'];
  64. $this->success('文件已经上传', $data, 200);
  65. } elseif ('local' === $data['uptype']) {
  66. $data['url'] = LocalStorage::instance()->url($data['key'], $safe, $name);
  67. $data['server'] = LocalStorage::instance()->upload();
  68. } elseif ('qiniu' === $data['uptype']) {
  69. $data['url'] = QiniuStorage::instance()->url($data['key'], $safe, $name);
  70. $data['token'] = QiniuStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  71. $data['server'] = QiniuStorage::instance()->upload();
  72. } elseif ('alioss' === $data['uptype']) {
  73. $token = AliossStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  74. $data['url'] = $token['siteurl'];
  75. $data['policy'] = $token['policy'];
  76. $data['signature'] = $token['signature'];
  77. $data['OSSAccessKeyId'] = $token['keyid'];
  78. $data['server'] = AliossStorage::instance()->upload();
  79. } elseif ('txcos' === $data['uptype']) {
  80. $token = TxcosStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  81. $data['url'] = $token['siteurl'];
  82. $data['q-ak'] = $token['q-ak'];
  83. $data['policy'] = $token['policy'];
  84. $data['q-key-time'] = $token['q-key-time'];
  85. $data['q-signature'] = $token['q-signature'];
  86. $data['q-sign-algorithm'] = $token['q-sign-algorithm'];
  87. $data['server'] = TxcosStorage::instance()->upload();
  88. }
  89. $this->success('获取上传授权参数', $data, 404);
  90. }
  91. /**
  92. * 文件上传入口
  93. * @login true
  94. * @throws \think\db\exception\DataNotFoundException
  95. * @throws \think\db\exception\DbException
  96. * @throws \think\db\exception\ModelNotFoundException
  97. */
  98. public function file()
  99. {
  100. if (!($file = $this->getFile())->isValid()) {
  101. $this->error('文件上传异常,文件过大或未上传!');
  102. }
  103. $safeMode = $this->getSafe();
  104. $extension = strtolower($file->getOriginalExtension());
  105. $saveName = input('key') ?: Storage::name($file->getPathname(), $extension, '', 'md5_file');
  106. // 检查文件后缀是否被恶意修改
  107. if (ltrim(strtolower(strrchr($saveName, '.')), '.') !== $extension) {
  108. $this->error('文件后缀异常,请重新上传文件!');
  109. }
  110. // 屏蔽禁止上传指定后缀的文件
  111. if (!in_array($extension, str2arr(sysconf('storage.allow_exts')))) {
  112. $this->error('文件类型受限,请在后台配置规则!');
  113. }
  114. if (in_array($extension, ['sh', 'asp', 'bat', 'cmd', 'exe', 'php'])) {
  115. $this->error('文件安全保护,禁止上传可执行文件!');
  116. }
  117. try {
  118. if ($this->getType() === 'local') {
  119. $local = LocalStorage::instance();
  120. $distName = $local->path($saveName, $safeMode);
  121. $file->move(dirname($distName), basename($distName));
  122. $info = $local->info($saveName, $safeMode, $file->getOriginalName());
  123. if (in_array($extension, ['jpg', 'gif', 'png', 'bmp', 'jpeg', 'wbmp'])) {
  124. if ($this->imgNotSafe($distName) && $local->del($saveName)) {
  125. $this->error('图片未通过安全检查!');
  126. }
  127. [$width, $height] = getimagesize($distName);
  128. if (($width < 1 || $height < 1) && $local->del($saveName)) {
  129. $this->error('读取图片的尺寸失败!');
  130. }
  131. }
  132. } else {
  133. $bina = file_get_contents($file->getPathname());
  134. $info = Storage::instance($this->getType())->set($saveName, $bina, $safeMode, $file->getOriginalName());
  135. }
  136. if (isset($info['url'])) {
  137. $this->success('文件上传成功!', ['url' => $safeMode ? $saveName : $info['url']]);
  138. } else {
  139. $this->error('文件处理失败,请稍候再试!');
  140. }
  141. } catch (HttpResponseException $exception) {
  142. throw $exception;
  143. } catch (\Exception $exception) {
  144. $this->error($exception->getMessage());
  145. }
  146. }
  147. /**
  148. * 获取文件上传类型
  149. * @return boolean
  150. */
  151. private function getSafe(): bool
  152. {
  153. return boolval(input('safe', '0'));
  154. }
  155. /**
  156. * 获取文件上传方式
  157. * @return string
  158. * @throws \think\db\exception\DataNotFoundException
  159. * @throws \think\db\exception\DbException
  160. * @throws \think\db\exception\ModelNotFoundException
  161. */
  162. private function getType(): string
  163. {
  164. $type = strtolower(input('uptype', ''));
  165. if (in_array($type, ['local', 'qiniu', 'alioss', 'txcos'])) {
  166. return $type;
  167. } else {
  168. return strtolower(sysconf('storage.type'));
  169. }
  170. }
  171. /**
  172. * 获取本地文件对象
  173. * @return UploadedFile
  174. */
  175. private function getFile(): UploadedFile
  176. {
  177. try {
  178. $file = $this->request->file('file');
  179. if ($file instanceof UploadedFile) {
  180. return $file;
  181. } else {
  182. $this->error('未获取到上传的文件对象!');
  183. }
  184. } catch (HttpResponseException $exception) {
  185. throw $exception;
  186. } catch (\Exception $exception) {
  187. $this->error(lang($exception->getMessage()));
  188. }
  189. }
  190. /**
  191. * 检查图片是否安全
  192. * @param string $filename
  193. * @return boolean
  194. */
  195. private function imgNotSafe(string $filename): bool
  196. {
  197. $source = fopen($filename, 'rb');
  198. if (($size = filesize($filename)) > 512) {
  199. $hexs = bin2hex(fread($source, 512));
  200. fseek($source, $size - 512);
  201. $hexs .= bin2hex(fread($source, 512));
  202. } else {
  203. $hexs = bin2hex(fread($source, $size));
  204. }
  205. if (is_resource($source)) fclose($source);
  206. $bins = hex2bin($hexs);
  207. /* 匹配十六进制中的 <% ( ) %> 或 <? ( ) ?> 或 <script | /script> */
  208. foreach (['<?php ', '<% ', '<script '] as $key) if (stripos($bins, $key) !== false) return true;
  209. return preg_match("/(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexs);
  210. }
  211. }