Server.php 2.7 KB

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