feat(images): serve stored images via API
This commit is contained in:
parent
97d5614397
commit
200193a999
2 changed files with 49 additions and 0 deletions
45
backend/app/Http/Controllers/ImageController.php
Normal file
45
backend/app/Http/Controllers/ImageController.php
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ImageController extends Controller
|
||||
{
|
||||
public function index(string $path): Response
|
||||
{
|
||||
$cleanPath = ltrim($path, '/');
|
||||
|
||||
if ($cleanPath === '' || Str::contains($cleanPath, ['../', '..\\'])) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$disk = Storage::disk('images');
|
||||
|
||||
if (! $disk->exists($cleanPath)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$file = $disk->get($cleanPath);
|
||||
|
||||
if ($file === null) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$contentType = match (strtolower(pathinfo($cleanPath, PATHINFO_EXTENSION))) {
|
||||
'jpg', 'jpeg' => 'image/jpeg',
|
||||
'png' => 'image/png',
|
||||
'webp' => 'image/webp',
|
||||
'gif' => 'image/gif',
|
||||
'svg' => 'image/svg+xml',
|
||||
default => 'application/octet-stream',
|
||||
};
|
||||
|
||||
return response($file, 200, [
|
||||
'Content-Type' => $contentType,
|
||||
'Cache-Control' => 'public, max-age=31536000, immutable',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
<?php
|
||||
|
||||
use App\Http\Controllers\CategoryController;
|
||||
use App\Http\Controllers\ImageController;
|
||||
use App\Http\Controllers\ProductController;
|
||||
use App\Http\Resources\UserResource;
|
||||
use Illuminate\Http\Request;
|
||||
|
|
@ -9,6 +10,9 @@ use Illuminate\Support\Facades\Route;
|
|||
Route::get('/products', [ProductController::class, 'index']);
|
||||
Route::get('/categories', [CategoryController::class, 'index']);
|
||||
|
||||
Route::get('/image/{path}', [ImageController::class, 'index'])
|
||||
->where('path', '.*');
|
||||
|
||||
Route::middleware('auth:sanctum')->group(function() {
|
||||
Route::get('/user', fn (Request $request) => new UserResource($request->user()));
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue