Server.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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 think\Request;
  11. use think\Exception;
  12. /**
  13. * 存储引擎抽象类
  14. * Class server
  15. * @package app\common\library\storage\drivers
  16. */
  17. abstract class Server
  18. {
  19. /* @var $file \think\File */
  20. protected $file;
  21. protected $error;
  22. protected $fileName;
  23. protected $fileInfo;
  24. // 是否为内部上传
  25. protected $isInternal = false;
  26. /**
  27. * 构造函数
  28. * Server constructor.
  29. */
  30. protected function __construct()
  31. {
  32. }
  33. /**
  34. * 设置上传的文件信息
  35. * @param string $name
  36. * @throws Exception
  37. */
  38. public function setUploadFile($name)
  39. {
  40. // 接收上传的文件
  41. $this->file = Request::instance()->file($name);
  42. if (empty($this->file)) {
  43. throw new Exception('未找到上传文件的信息');
  44. }
  45. // 文件信息
  46. $this->fileInfo = $this->file->getInfo();
  47. // 生成保存文件名
  48. $this->fileName = $this->buildSaveName();
  49. }
  50. /**
  51. * 设置上传的文件信息
  52. * @param string $filePath
  53. */
  54. public function setUploadFileByReal($filePath)
  55. {
  56. // 设置为系统内部上传
  57. $this->isInternal = true;
  58. // 文件信息
  59. $this->fileInfo = [
  60. 'name' => basename($filePath),
  61. 'size' => filesize($filePath),
  62. 'tmp_name' => $filePath,
  63. 'error' => 0,
  64. ];
  65. // 生成保存文件名
  66. $this->fileName = $this->buildSaveName();
  67. }
  68. /**
  69. * 文件上传
  70. * @return mixed
  71. */
  72. abstract protected function upload();
  73. /**
  74. * 文件删除
  75. * @param $fileName
  76. * @return mixed
  77. */
  78. abstract protected function delete($fileName);
  79. /**
  80. * 返回上传后文件路径
  81. * @return mixed
  82. */
  83. abstract public function getFileName();
  84. /**
  85. * 返回文件信息
  86. * @return mixed
  87. */
  88. public function getFileInfo()
  89. {
  90. return $this->fileInfo;
  91. }
  92. protected function getRealPath()
  93. {
  94. return $this->getFileInfo()['tmp_name'];
  95. }
  96. /**
  97. * 返回错误信息
  98. * @return mixed
  99. */
  100. public function getError()
  101. {
  102. return $this->error;
  103. }
  104. /**
  105. * 生成保存文件名
  106. */
  107. private function buildSaveName()
  108. {
  109. // 要上传图片的本地路径
  110. $realPath = $this->getRealPath();
  111. // 扩展名
  112. $ext = pathinfo($this->getFileInfo()['name'], PATHINFO_EXTENSION);
  113. // 自动生成文件名
  114. return date('YmdHis') . substr(md5($realPath), 0, 5)
  115. . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT) . ".{$ext}";
  116. }
  117. }