| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- <?php
- namespace App\Module\File\Services;
- use App\Module\File\Config\StorageConfig;
- use Illuminate\Support\Facades\Storage;
- /**
- * 临时文件服务类
- *
- * 提供临时文件处理相关的服务
- */
- class TemporaryService
- {
- /**
- * 获取临时文件存储磁盘
- *
- * @return \Illuminate\Contracts\Filesystem\Filesystem
- */
- private function getDisk()
- {
- $storage = StorageConfig::getStorage();
- $tempStorage = env('FILESYSTEM_TEMP_DISK', $storage);
- return Storage::disk($tempStorage);
- }
- /**
- * 获取临时文件目录
- *
- * @return string 临时文件目录
- */
- public function getDir()
- {
- return config('app.name') . '_temp/' . date('Ym/d/');
- }
- /**
- * 获取临时文件存储路径
- *
- * @param string $ext 文件扩展名
- * @return string 存储路径
- */
- private function getStorePath($ext)
- {
- $path = $this->getDir() . uniqid() . '.' . $ext;
- return $path;
- }
- /**
- * 保存临时文件
- *
- * @param string $ext 文件扩展名
- * @param string $fileString 文件内容
- * @return string 存储路径
- * @throws \Exception 存储失败时抛出异常
- */
- public function save($ext, $fileString)
- {
- $path = $this->getStorePath($ext);
- $res = $this->getDisk()->put($path, $fileString);
- if (!$res) {
- throw new \Exception("临时储存失败");
- }
- return $path;
- }
- /**
- * 获取临时文件下载URL
- *
- * @param string $path 文件路径
- * @return string 下载URL
- */
- public function getDownUrl($path)
- {
- $path = config('app.name') . '_temp/' . $path;
- $res = $this->getDisk()->url($path);
- return $res;
- }
- /**
- * 获取临时文件下载响应
- *
- * @param string $path 文件路径
- * @return \Illuminate\Http\Response 下载响应
- */
- public function getDown($path)
- {
- $path = config('app.name') . '_temp/' . $path;
- $disk = $this->getDisk();
- $res = $disk->read($path);
- $headers = [];
- $headers['Content-Type'] = $disk->mimeType($path);
- $headers['Content-Length'] = $disk->size($path);
- $resp = response('', 200, $headers)->setContent($res);
- return $resp;
- }
- /**
- * 路径转URL
- *
- * @param string $path 文件路径
- * @return string URL
- */
- public function path2url($path)
- {
- $new = substr($path, strpos($path, 'temp'));
- return $new;
- }
- /**
- * 获取本地临时文件路径
- *
- * @return string 本地临时文件路径
- */
- public function getTempLocalFile()
- {
- $file = sys_get_temp_dir() . '/' . uniqid();
- return $file;
- }
- }
|