TemporaryService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. <?php
  2. namespace App\Module\File\Services;
  3. use App\Module\File\Config\StorageConfig;
  4. use Illuminate\Support\Facades\Storage;
  5. /**
  6. * 临时文件服务类
  7. *
  8. * 提供临时文件处理相关的服务
  9. */
  10. class TemporaryService
  11. {
  12. /**
  13. * 获取临时文件存储磁盘
  14. *
  15. * @return \Illuminate\Contracts\Filesystem\Filesystem
  16. */
  17. private function getDisk()
  18. {
  19. $storage = StorageConfig::getStorage();
  20. $tempStorage = env('FILESYSTEM_TEMP_DISK', $storage);
  21. return Storage::disk($tempStorage);
  22. }
  23. /**
  24. * 获取临时文件目录
  25. *
  26. * @return string 临时文件目录
  27. */
  28. public function getDir()
  29. {
  30. return config('app.name') . '_temp/' . date('Ym/d/');
  31. }
  32. /**
  33. * 获取临时文件存储路径
  34. *
  35. * @param string $ext 文件扩展名
  36. * @return string 存储路径
  37. */
  38. private function getStorePath($ext)
  39. {
  40. $path = $this->getDir() . uniqid() . '.' . $ext;
  41. return $path;
  42. }
  43. /**
  44. * 保存临时文件
  45. *
  46. * @param string $ext 文件扩展名
  47. * @param string $fileString 文件内容
  48. * @return string 存储路径
  49. * @throws \Exception 存储失败时抛出异常
  50. */
  51. public function save($ext, $fileString)
  52. {
  53. $path = $this->getStorePath($ext);
  54. $res = $this->getDisk()->put($path, $fileString);
  55. if (!$res) {
  56. throw new \Exception("临时储存失败");
  57. }
  58. return $path;
  59. }
  60. /**
  61. * 获取临时文件下载URL
  62. *
  63. * @param string $path 文件路径
  64. * @return string 下载URL
  65. */
  66. public function getDownUrl($path)
  67. {
  68. $path = config('app.name') . '_temp/' . $path;
  69. $res = $this->getDisk()->url($path);
  70. return $res;
  71. }
  72. /**
  73. * 获取临时文件下载响应
  74. *
  75. * @param string $path 文件路径
  76. * @return \Illuminate\Http\Response 下载响应
  77. */
  78. public function getDown($path)
  79. {
  80. $path = config('app.name') . '_temp/' . $path;
  81. $disk = $this->getDisk();
  82. $res = $disk->read($path);
  83. $headers = [];
  84. $headers['Content-Type'] = $disk->mimeType($path);
  85. $headers['Content-Length'] = $disk->size($path);
  86. $resp = response('', 200, $headers)->setContent($res);
  87. return $resp;
  88. }
  89. /**
  90. * 路径转URL
  91. *
  92. * @param string $path 文件路径
  93. * @return string URL
  94. */
  95. public function path2url($path)
  96. {
  97. $new = substr($path, strpos($path, 'temp'));
  98. return $new;
  99. }
  100. /**
  101. * 获取本地临时文件路径
  102. *
  103. * @return string 本地临时文件路径
  104. */
  105. public function getTempLocalFile()
  106. {
  107. $file = sys_get_temp_dir() . '/' . uniqid();
  108. return $file;
  109. }
  110. }