Upload.php 8.0 KB

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