Fileoper.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: sicilon_IT
  5. * Date: 2020/1/5
  6. * Time: 9:49
  7. */
  8. namespace app\index\controller;
  9. use think\Controller;
  10. use think\facade\Log;
  11. use think\Request;
  12. class Fileoper extends Controller
  13. {
  14. private function filterfiletype($usefile = "file")
  15. {
  16. $filetype = $_FILES[$usefile]['type'];
  17. $types = [
  18. 'image',
  19. 'excel',
  20. ];
  21. $filetypeuse = "*" . $filetype;
  22. $iscanupload = false;
  23. foreach ($types as $key => $value) {
  24. if (strpos($filetypeuse, $value)) {
  25. $iscanupload = true;
  26. }
  27. }
  28. if (!$iscanupload) {
  29. log::info($_FILES);
  30. $msg = "file type error: " . $filetype;
  31. log::info($msg);
  32. $this->error($msg);
  33. }
  34. }
  35. /**
  36. * 指定文件位置上传
  37. *
  38. * @return void
  39. */
  40. public function uploadfilebydir()
  41. {
  42. Log::info($_FILES);
  43. $this->filterfiletype();
  44. // 获取表单上传文件
  45. $file = request()->file('file');
  46. if (empty($file)) {
  47. $this->error('请选择上传文件');
  48. }
  49. $dir = request()->param('dir', 'appointment');
  50. if (!preg_match("/^[a-z]{5,30}$/", $dir)) {
  51. $this->error('请求错误');
  52. }
  53. $dir = 'Uploads' . '/' . $dir;
  54. $domainpath = getselfurl() . '/' . $dir . '/';
  55. // 移动到框架应用根目录/public/uploads/ 目录下
  56. $info = $file->move(ROOT_PATH . 'public' . '/' . $dir);
  57. //如果不清楚文件上传的具体键名,可以直接打印$info来查看
  58. //获取文件(文件名),$info->getFilename() ***********不同之处,笔记笔记哦
  59. //获取文件(日期/文件名),$info->getSaveName() **********不同之处,笔记笔记哦
  60. $filename = $info->getSaveName(); //在测试的时候也可以直接打印文件名称来查看
  61. $filename = str_replace(DS, "/", $filename);
  62. if ($filename) {
  63. //$this->success('文件上传成功!');
  64. $imageUrl = $domainpath . $filename;
  65. $r_upload['code'] = '200';
  66. $r_upload['resultData'] = $imageUrl;
  67. //不转义反斜杠
  68. return json_encode($r_upload, 320);
  69. } else {
  70. // 上传失败获取错误信息
  71. $this->error($file->getError());
  72. }
  73. }
  74. }