Upload.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. $this->success('文件已经上传', $data, 200);
  64. } elseif ('local' === $data['uptype']) {
  65. $data['url'] = LocalStorage::instance()->url($data['key'], $safe, $name);
  66. $data['server'] = LocalStorage::instance()->upload();
  67. } elseif ('qiniu' === $data['uptype']) {
  68. $data['url'] = QiniuStorage::instance()->url($data['key'], $safe, $name);
  69. $data['token'] = QiniuStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  70. $data['server'] = QiniuStorage::instance()->upload();
  71. } elseif ('alioss' === $data['uptype']) {
  72. $token = AliossStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  73. $data['url'] = $token['siteurl'];
  74. $data['policy'] = $token['policy'];
  75. $data['signature'] = $token['signature'];
  76. $data['OSSAccessKeyId'] = $token['keyid'];
  77. $data['server'] = AliossStorage::instance()->upload();
  78. } elseif ('txcos' === $data['uptype']) {
  79. $token = TxcosStorage::instance()->buildUploadToken($data['key'], 3600, $name);
  80. $data['url'] = $token['siteurl'];
  81. $data['q-ak'] = $token['q-ak'];
  82. $data['policy'] = $token['policy'];
  83. $data['q-key-time'] = $token['q-key-time'];
  84. $data['q-signature'] = $token['q-signature'];
  85. $data['q-sign-algorithm'] = $token['q-sign-algorithm'];
  86. $data['server'] = TxcosStorage::instance()->upload();
  87. }
  88. $this->success('获取上传授权参数', $data, 404);
  89. }
  90. /**
  91. * 文件上传入口
  92. * @login true
  93. * @throws \think\db\exception\DataNotFoundException
  94. * @throws \think\db\exception\DbException
  95. * @throws \think\db\exception\ModelNotFoundException
  96. */
  97. public function file()
  98. {
  99. if (!($file = $this->getFile())->isValid()) {
  100. $this->error('文件上传异常,文件过大或未上传!');
  101. }
  102. $safeMode = $this->getSafe();
  103. $extension = strtolower($file->getOriginalExtension());
  104. $saveName = input('key') ?: Storage::name($file->getPathname(), $extension, '', 'md5_file');
  105. // 检查文件后缀是否被恶意修改
  106. if (ltrim(strtolower(strrchr($saveName, '.')), '.') !== $extension) {
  107. $this->error('文件后缀异常,请重新上传文件!');
  108. }
  109. // 屏蔽禁止上传指定后缀的文件
  110. if (!in_array($extension, str2arr(sysconf('storage.allow_exts')))) {
  111. $this->error('文件类型受限,请在后台配置规则!');
  112. }
  113. if (in_array($extension, ['sh', 'asp', 'bat', 'cmd', 'exe', 'php'])) {
  114. $this->error('文件安全保护,禁止上传可执行文件!');
  115. }
  116. try {
  117. if ($this->getType() === 'local') {
  118. $local = LocalStorage::instance();
  119. $distName = $local->path($saveName, $safeMode);
  120. $file->move(dirname($distName), basename($distName));
  121. $info = $local->info($saveName, $safeMode, $file->getOriginalName());
  122. if (in_array($extension, ['jpg', 'gif', 'png', 'bmp', 'jpeg', 'wbmp'])) {
  123. if ($this->imgNotSafe($distName) && $local->del($saveName)) {
  124. $this->error('图片未通过安全检查!');
  125. }
  126. [$width, $height] = getimagesize($distName);
  127. if (($width < 1 || $height < 1) && $local->del($saveName)) {
  128. $this->error('读取图片的尺寸失败!');
  129. }
  130. }
  131. } else {
  132. $bina = file_get_contents($file->getPathname());
  133. $info = Storage::instance($this->getType())->set($saveName, $bina, $safeMode, $file->getOriginalName());
  134. }
  135. if (isset($info['url'])) {
  136. $this->success('文件上传成功!', ['url' => $safeMode ? $saveName : $info['url']]);
  137. } else {
  138. $this->error('文件处理失败,请稍候再试!');
  139. }
  140. } catch (HttpResponseException $exception) {
  141. throw $exception;
  142. } catch (\Exception $exception) {
  143. $this->error($exception->getMessage());
  144. }
  145. }
  146. /**
  147. * 获取文件上传类型
  148. * @return boolean
  149. */
  150. private function getSafe(): bool
  151. {
  152. return boolval(input('safe', '0'));
  153. }
  154. /**
  155. * 获取文件上传方式
  156. * @return string
  157. * @throws \think\db\exception\DataNotFoundException
  158. * @throws \think\db\exception\DbException
  159. * @throws \think\db\exception\ModelNotFoundException
  160. */
  161. private function getType(): string
  162. {
  163. $type = strtolower(input('uptype', ''));
  164. if (in_array($type, ['local', 'qiniu', 'alioss', 'txcos'])) {
  165. return $type;
  166. } else {
  167. return strtolower(sysconf('storage.type'));
  168. }
  169. }
  170. /**
  171. * 获取本地文件对象
  172. * @return UploadedFile
  173. */
  174. private function getFile(): UploadedFile
  175. {
  176. try {
  177. $file = $this->request->file('file');
  178. if ($file instanceof UploadedFile) {
  179. return $file;
  180. } else {
  181. $this->error('未获取到上传的文件对象!');
  182. }
  183. } catch (HttpResponseException $exception) {
  184. throw $exception;
  185. } catch (\Exception $exception) {
  186. $this->error(lang($exception->getMessage()));
  187. }
  188. }
  189. /**
  190. * 检查图片是否安全
  191. * @param string $filename
  192. * @return boolean
  193. */
  194. private function imgNotSafe(string $filename): bool
  195. {
  196. $source = fopen($filename, 'rb');
  197. if (($size = filesize($filename)) > 512) {
  198. $hexs = bin2hex(fread($source, 512));
  199. fseek($source, $size - 512);
  200. $hexs .= bin2hex(fread($source, 512));
  201. } else {
  202. $hexs = bin2hex(fread($source, $size));
  203. }
  204. if (is_resource($source)) fclose($source);
  205. $bins = hex2bin($hexs);
  206. /* 匹配十六进制中的 <% ( ) %> 或 <? ( ) ?> 或 <script | /script> */
  207. foreach (['<?php ', '<% ', '<script '] as $key) if (stripos($bins, $key) !== false) return true;
  208. return preg_match("/(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexs);
  209. }
  210. }