UploadFile.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\librarys\storage;
  8. class UploadFile extends \yii\web\UploadedFile
  9. {
  10. protected $driver;
  11. protected $basePath;
  12. /**
  13. * @param $file
  14. * @param bool $deleteTempFile
  15. * @return bool
  16. */
  17. public function saveAs($file, $deleteTempFile = true)
  18. {
  19. $result = false;
  20. // Todo is_uploaded_file($this->tempName)
  21. if ($this->error == UPLOAD_ERR_OK) {
  22. $result = $this->driver->saveFile($this->tempName, $this->getFullPath($file));
  23. }
  24. if ($result && $deleteTempFile) {
  25. $this->deleteTempFile();
  26. }
  27. return $result;
  28. }
  29. /**
  30. * @param $baseName
  31. * @param bool $deleteTempFile
  32. * @return bool|string
  33. */
  34. public function saveWithOriginalExtension($baseName, $deleteTempFile = true)
  35. {
  36. return $this->saveAs($baseName . '.' . $this->getExtension(), $deleteTempFile);
  37. }
  38. /**
  39. * @param $file
  40. * @return string
  41. */
  42. protected function getFullPath($file)
  43. {
  44. return rtrim($this->basePath, '/')
  45. . '/'
  46. . ltrim($file, '/');
  47. }
  48. /**
  49. * @return bool
  50. */
  51. public function deleteTempFile()
  52. {
  53. return unlink($this->tempName);
  54. }
  55. /**
  56. * @param $name
  57. * @param $driver
  58. * @param $basePath
  59. * @return \yii\web\UploadedFile[]
  60. */
  61. public static function getInstancesByStorage($name, $driver, $basePath)
  62. {
  63. parent::reset();
  64. $instances = parent::getInstancesByName($name);
  65. foreach ($instances as $key => $instance) {
  66. if ($instance instanceof self) {
  67. $instance->driver = $driver;
  68. $instance->basePath = $basePath;
  69. continue;
  70. }
  71. unset($instances[$key]);
  72. }
  73. return $instances;
  74. }
  75. /**
  76. * @param $name
  77. * @param $driver
  78. * @param $basePath
  79. * @return mixed|\yii\web\UploadedFile|static|null
  80. */
  81. public static function getInstanceByStorage($name, $driver, $basePath)
  82. {
  83. parent::reset();
  84. $instance = parent::getInstanceByName($name);
  85. if ($instance instanceof self) {
  86. $instance->driver = $driver;
  87. $instance->basePath = $basePath;
  88. }
  89. return $instance;
  90. }
  91. }