Local.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace app\common\library\storage\engine;
  3. use app\common\library\helper;
  4. /**
  5. * 本地文件驱动
  6. * Class Local
  7. * @package app\common\library\storage\drivers
  8. */
  9. class Local extends Server
  10. {
  11. public function __construct()
  12. {
  13. parent::__construct();
  14. }
  15. /**
  16. * 上传图片文件
  17. * @return array|bool
  18. */
  19. public function upload()
  20. {
  21. return $this->isInternal ? $this->uploadByInternal() : $this->uploadByExternal();
  22. }
  23. /**
  24. * 外部上传(指用户上传,需验证文件类型、大小)
  25. * @return bool
  26. */
  27. private function uploadByExternal()
  28. {
  29. // 上传目录
  30. $uplodDir = WEB_PATH . 'uploads';
  31. // 验证文件并上传
  32. $info = $this->file->validate([
  33. 'size' => 4 * 1024 * 1024,
  34. 'ext' => 'jpg,jpeg,png,gif'
  35. ])->move($uplodDir, $this->fileName);
  36. if (empty($info)) {
  37. $this->error = $this->file->getError();
  38. return false;
  39. }
  40. return true;
  41. }
  42. /**
  43. * 内部上传(指系统上传,信任模式)
  44. * @return bool
  45. */
  46. private function uploadByInternal()
  47. {
  48. // 上传目录
  49. $uplodDir = WEB_PATH . 'uploads';
  50. // 要上传图片的本地路径
  51. $realPath = $this->getRealPath();
  52. if (!rename($realPath, "{$uplodDir}/$this->fileName")) {
  53. $this->error = 'upload write error';
  54. return false;
  55. }
  56. return true;
  57. }
  58. /**
  59. * 删除文件
  60. * @param $fileName
  61. * @return bool|mixed
  62. */
  63. public function delete($fileName)
  64. {
  65. // 文件所在目录
  66. $filePath = WEB_PATH . "uploads/{$fileName}";
  67. return !file_exists($filePath) ?: unlink($filePath);
  68. }
  69. /**
  70. * 返回文件路径
  71. * @return mixed
  72. */
  73. public function getFileName()
  74. {
  75. return $this->fileName;
  76. }
  77. }