Upload.php 9.1 KB

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