diff --git a/app/Http/Controllers/Admin/FileController.php b/app/Http/Controllers/Admin/FileController.php index 9d77b89..cb620b1 100644 --- a/app/Http/Controllers/Admin/FileController.php +++ b/app/Http/Controllers/Admin/FileController.php @@ -69,9 +69,15 @@ class FileController extends Controller $data['src'] = 'storage/'.$path.'/'.$file_name; $data['user_id'] = auth()->id(); $data['sts'] = 1; + $relativePath = $data['src']; $file_create = File::create($data); - $file_create->setAttribute('full_src', File::publicUrl($data['src'])); + $fullSrc = File::publicUrl($relativePath); - return response()->json($file_create->fresh()); + $payload = $file_create->fresh()->toArray(); + $payload['path'] = $relativePath; + $payload['full_src'] = $fullSrc; + $payload['src'] = $fullSrc; + + return response()->json($payload); } } diff --git a/app/Models/File.php b/app/Models/File.php index bb79204..5a4abc6 100644 --- a/app/Models/File.php +++ b/app/Models/File.php @@ -56,9 +56,12 @@ class File extends Model $relative = self::normalizeRelativeStoragePath($trimmed); $base = self::resolvePublicBaseUrl(); - if ($base === '' || $relative === '') { + if ($relative === '') { return null; } + if ($base === '') { + return $relative; + } return $base.'/'.$relative; } @@ -124,6 +127,17 @@ class File extends Model return self::ensureAbsoluteUrl(self::ensureServerPublicBase(rtrim($appUrl, '/'))); } + try { + if (app()->bound('request')) { + $request = request(); + $host = $request?->getSchemeAndHttpHost(); + if (is_string($host) && $host !== '' && ! str_contains($host, 'localhost')) { + return self::ensureAbsoluteUrl(self::ensureServerPublicBase($host)); + } + } + } catch (\Throwable) { + } + return ''; } diff --git a/tests/Unit/FilePublicUrlTest.php b/tests/Unit/FilePublicUrlTest.php index c43aa36..9dda6f8 100644 --- a/tests/Unit/FilePublicUrlTest.php +++ b/tests/Unit/FilePublicUrlTest.php @@ -51,4 +51,25 @@ class FilePublicUrlTest extends TestCase $this->assertSame('https://garoosigholaktala.ir/server', File::resolvePublicBaseUrl()); } + + public function test_public_url_falls_back_to_relative_path_when_base_unknown(): void + { + Config::set('app.domain', null); + Config::set('app.url', 'http://localhost'); + + $url = File::publicUrl('storage/1405/02/27/sample.jpg'); + + $this->assertSame('storage/1405/02/27/sample.jpg', $url); + } + + public function test_resolve_base_from_current_request_host(): void + { + Config::set('app.domain', null); + Config::set('app.url', 'http://localhost'); + + $request = \Illuminate\Http\Request::create('https://niazitala.ir/server/admin/file', 'POST'); + $this->app->instance('request', $request); + + $this->assertSame('https://niazitala.ir/server', File::resolvePublicBaseUrl()); + } }