Upload.php 9.1 KB

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