Local.php 2.0 KB

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