Upfile.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. *
  4. * User: anyluck
  5. * Date: 2020/4/17
  6. * Time: 9:56
  7. */
  8. namespace app\common\controller;
  9. use think\facade\Request;
  10. use lemo\helper\DataHelper;
  11. class Upfile
  12. {
  13. //上传验证规则
  14. protected $uploadValidate = [
  15. 'image' => 'filesize:102400|fileExt:jpg,png,gif,jpeg,rar,zip,avi,mp4,rmvb,3gp,flv,mp3,txt,doc,xls,ppt,pdf,xls,docx,xlsx,doc,wmv'
  16. ];
  17. protected $imageValidate = [
  18. 'image' => 'filesize:10240|fileExt:jpg,png,gif,jpeg,bmp,svg,wmv'
  19. ];
  20. protected $videoValidate = [
  21. 'file' => 'filesize:10240|avi,rmvb,3gp,flv,mp4,wmv'
  22. ];
  23. protected $voiceValidate = [
  24. 'file' => 'filesize:2048|mp3,wma,wav,amr,wmv'
  25. ];
  26. public function initialize()
  27. {
  28. $fileExt = getConfigByCode('upload_file_type');
  29. $filemax = getConfigByCode('upload_file_max') * 1024;
  30. $this->uploadValidate = ['image' =>
  31. 'filesize' . $filemax . '|' . $fileExt,
  32. ];
  33. parent::initialize(); // TODO: Change the autogenerated stub
  34. }
  35. // TODO 文件类处理
  36. /**
  37. * 文件上传
  38. * @return false|string
  39. */
  40. public function Uploads()
  41. {
  42. //获取上传文件表单字段名
  43. $fileKey = array_keys(request()->file());
  44. for ($i = 0; $i < count($fileKey); $i++) {
  45. //获取表单上传文件
  46. $file = request()->file($fileKey[$i]);
  47. try {
  48. validate($this->uploadValidate)->check(DataHelper::objToArray($file));
  49. $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
  50. $savename = str_replace('\\', "/", $savename);
  51. $path[] = '/storage/' . $savename;
  52. } catch (\think\exception\ValidateException $e) {
  53. $path = '';
  54. $error = $e->getMessage();
  55. }
  56. }
  57. if (!empty($path)) {
  58. $result['code'] = 1;
  59. //分辨是否截图上传,截图上传只能上传一个,非截图上传可以上传多个
  60. if (Request::param('responseType') == 'json') {
  61. $result["url"] = $path[0];
  62. } else {
  63. $result["url"] = $path;
  64. }
  65. $result['msg'] = lang('upload success');
  66. return $result;
  67. } else {
  68. //上传失败获取错误信息
  69. $result['url'] = '';
  70. $result['msg'] = $error;
  71. $result['code'] = 0;
  72. return $result;
  73. }
  74. }
  75. }