Temporary.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. <?php
  2. namespace App\Module\File;
  3. use UCore\Exception\LogicException;
  4. use Illuminate\Support\Facades\Storage;
  5. class Temporary
  6. {
  7. /**
  8. *
  9. * @return \Illuminate\Contracts\Filesystem\Filesystem
  10. */
  11. private static function getDisk()
  12. {
  13. $storage = \App\Module\File\Storage::getStorage();
  14. $tempStorage = env('FILESYSTEM_TEMP_DISK', $storage);
  15. return Storage::disk($tempStorage);
  16. }
  17. static public function getDir()
  18. {
  19. return config('app.name') . '_temp/' . date('Ym/d/');
  20. }
  21. /**
  22. * 获取储存地址
  23. *
  24. * @param $ext
  25. * @return string
  26. */
  27. static private function getStorePath($ext)
  28. {
  29. $path = self::getDir() . uniqid() . '.' . $ext;
  30. return $path;
  31. }
  32. static public function save($ext, $fileString)
  33. {
  34. $path = self::getStorePath($ext);
  35. $res = self::getDisk()->put($path, $fileString);
  36. if (!$res) {
  37. throw new LogicException("临时储存失败");
  38. }
  39. return $path;
  40. }
  41. /**
  42. * 读取并下载
  43. *
  44. * @param $path
  45. * @return \Symfony\Component\HttpFoundation\StreamedResponse
  46. */
  47. static public function getDownUrl($path)
  48. {
  49. $path = config('app.name') . '_temp/' . $path;
  50. // dd($path);
  51. $res = self::getDisk()->url($path);
  52. return $res;
  53. }
  54. static public function getDown($path)
  55. {
  56. $path = config('app.name') . '_temp/' . $path;
  57. // dd($path);
  58. $disk = self::getDisk();
  59. // dd($oss);
  60. $res = $disk->read($path);
  61. $headers = [];
  62. $headers['Content-Type'] = $disk->mimeType($path);
  63. $headers['Content-Length'] = $disk->size($path);
  64. // dd($headers);
  65. $resp = response('', 200, $headers)->setContent($res);
  66. // dd($res);
  67. return $resp;
  68. }
  69. static public function path2url($path)
  70. {
  71. $new = substr($path, strpos($path, 'temp'));
  72. return $new;
  73. }
  74. /**
  75. * 获取本地驱动的临时文件一个
  76. *
  77. * @return string
  78. */
  79. static public function getTempLocalFile()
  80. {
  81. $file = sys_get_temp_dir() . '/' . uniqid();
  82. // dd($file);
  83. return $file;
  84. }
  85. }