Upload.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. use think\response\Json;
  26. /**
  27. * 文件上传接口
  28. * Class Upload
  29. * @package app\admin\controller\api
  30. */
  31. class Upload extends Controller
  32. {
  33. /**
  34. * 文件上传方式
  35. * @var string
  36. */
  37. private $type;
  38. /**
  39. * 文件上传模式
  40. * @var boolean
  41. */
  42. private $safe;
  43. /**
  44. * 文件上传脚本
  45. * @return Response
  46. * @throws \think\db\exception\DataNotFoundException
  47. * @throws \think\db\exception\DbException
  48. * @throws \think\db\exception\ModelNotFoundException
  49. */
  50. public function index(): Response
  51. {
  52. $data = ['exts' => []];
  53. foreach (str2arr(sysconf('storage.allow_exts')) as $ext) {
  54. $data['exts'][$ext] = Storage::mime($ext);
  55. }
  56. $template = realpath(__DIR__ . '/../../view/api/upload.js');
  57. $data['exts'] = json_encode($data['exts'], JSON_UNESCAPED_UNICODE);
  58. return view($template, $data)->contentType('application/x-javascript');
  59. }
  60. /**
  61. * 文件上传检查
  62. * @login true
  63. * @throws \think\admin\Exception
  64. * @throws \think\db\exception\DataNotFoundException
  65. * @throws \think\db\exception\DbException
  66. * @throws \think\db\exception\ModelNotFoundException
  67. */
  68. public function state()
  69. {
  70. [$this->name, $this->safe] = [input('name', null), $this->getSafe()];
  71. $data = ['uptype' => $this->getType(), 'safe' => intval($this->safe), 'key' => input('key')];
  72. if ($info = Storage::instance($data['uptype'])->info($data['key'], $this->safe, $this->name)) {
  73. $data['url'] = $info['url'];
  74. $this->success('文件已经上传', $data, 200);
  75. } elseif ('local' === $data['uptype']) {
  76. $data['url'] = LocalStorage::instance()->url($data['key'], $this->safe, $this->name);
  77. $data['server'] = LocalStorage::instance()->upload();
  78. } elseif ('qiniu' === $data['uptype']) {
  79. $data['url'] = QiniuStorage::instance()->url($data['key'], $this->safe, $this->name);
  80. $data['token'] = QiniuStorage::instance()->buildUploadToken($data['key'], 3600, $this->name);
  81. $data['server'] = QiniuStorage::instance()->upload();
  82. } elseif ('alioss' === $data['uptype']) {
  83. $token = AliossStorage::instance()->buildUploadToken($data['key'], 3600, $this->name);
  84. $data['url'] = $token['siteurl'];
  85. $data['policy'] = $token['policy'];
  86. $data['signature'] = $token['signature'];
  87. $data['OSSAccessKeyId'] = $token['keyid'];
  88. $data['server'] = AliossStorage::instance()->upload();
  89. } elseif ('txcos' === $data['uptype']) {
  90. $token = TxcosStorage::instance()->buildUploadToken($data['key'], 3600, $this->name);
  91. $data['url'] = $token['siteurl'];
  92. $data['q-ak'] = $token['q-ak'];
  93. $data['policy'] = $token['policy'];
  94. $data['q-key-time'] = $token['q-key-time'];
  95. $data['q-signature'] = $token['q-signature'];
  96. $data['q-sign-algorithm'] = $token['q-sign-algorithm'];
  97. $data['server'] = TxcosStorage::instance()->upload();
  98. }
  99. $this->success('获取上传授权参数', $data, 404);
  100. }
  101. /**
  102. * 文件上传入口
  103. * @login true
  104. * @return Json
  105. * @throws \think\db\exception\DataNotFoundException
  106. * @throws \think\db\exception\DbException
  107. * @throws \think\db\exception\ModelNotFoundException
  108. */
  109. public function file(): Json
  110. {
  111. if (!($file = $this->getFile())->isValid()) {
  112. return json(['uploaded' => false, 'error' => ['message' => '文件上传异常,文件过大或未上传!']]);
  113. }
  114. $extension = strtolower($file->getOriginalExtension());
  115. [$pathname, $original] = [$file->getPathname(), $file->getOriginalName()];
  116. if (!in_array($extension, str2arr(sysconf('storage.allow_exts')))) {
  117. return json(['uploaded' => false, 'error' => ['message' => '文件类型受限,请在后台配置规则!']]);
  118. }
  119. if (in_array($extension, ['sh', 'asp', 'bat', 'cmd', 'exe', 'php'])) {
  120. return json(['uploaded' => false, 'error' => ['message' => '文件安全保护,可执行文件禁止上传!']]);
  121. }
  122. [$this->type, $this->safe] = [$this->getType(), $this->getSafe()];
  123. $this->name = input('key') ?: Storage::name($pathname, $extension, '', 'md5_file');
  124. try {
  125. if ($this->type === 'local') {
  126. $local = LocalStorage::instance();
  127. $distname = $local->path($this->name, $this->safe);
  128. $file->move(dirname($distname), basename($distname));
  129. $info = $local->info($this->name, $this->safe, $original);
  130. if (in_array($extension, ['jpg', 'gif', 'png', 'bmp', 'jpeg', 'wbmp'])) {
  131. [$width, $height] = getimagesize($distname);
  132. if ($width < 1 || $height < 1 && $local->del($this->name)) {
  133. return json(['uploaded' => false, 'error' => ['message' => '图片尺寸读取失败!']]);
  134. }
  135. }
  136. } else {
  137. $bina = file_get_contents($pathname);
  138. $info = Storage::instance($this->type)->set($this->name, $bina, $this->safe, $original);
  139. }
  140. } catch (HttpResponseException $exception) {
  141. throw $exception;
  142. } catch (\Exception $exception) {
  143. return json(['uploaded' => false, 'error' => ['message' => $exception->getMessage()]]);
  144. }
  145. if (is_array($info) && isset($info['url'])) {
  146. return json(['uploaded' => true, 'filename' => $this->name, 'url' => $this->safe ? $this->name : $info['url']]);
  147. } else {
  148. return json(['uploaded' => false, 'error' => ['message' => '文件处理失败,请稍候再试!']]);
  149. }
  150. }
  151. /**
  152. * 获取文件上传类型
  153. * @return boolean
  154. */
  155. private function getSafe(): bool
  156. {
  157. return boolval(input('safe', '0'));
  158. }
  159. /**
  160. * 获取文件上传方式
  161. * @return string
  162. * @throws \think\db\exception\DataNotFoundException
  163. * @throws \think\db\exception\DbException
  164. * @throws \think\db\exception\ModelNotFoundException
  165. */
  166. private function getType(): string
  167. {
  168. $this->type = strtolower(input('uptype', ''));
  169. if (!in_array($this->type, ['local', 'qiniu', 'alioss', 'txcos'])) {
  170. $this->type = strtolower(sysconf('storage.type'));
  171. }
  172. return strtolower($this->type);
  173. }
  174. /**
  175. * 获取本地文件对象
  176. * @return UploadedFile
  177. */
  178. private function getFile(): UploadedFile
  179. {
  180. try {
  181. $file = $this->request->file('file');
  182. if ($file instanceof UploadedFile) {
  183. return $file;
  184. } else {
  185. $this->error('未获取到上传的文件对象!');
  186. }
  187. } catch (HttpResponseException $exception) {
  188. throw $exception;
  189. } catch (\Exception $exception) {
  190. $this->error(lang($exception->getMessage()));
  191. }
  192. }
  193. }