Laravel本地驱动下Filament的FileUpload组件无法显示图片求助
解决Filament使用local驱动时图片显示破碎的问题
1. 创建私有文件访问路由
在routes/web.php中添加路由,代理访问local驱动下的图片文件:
use Illuminate\Support\Facades\Storage; use Illuminate\Http\Response; Route::get('/tool-photos/{filename}', function ($filename) { $filePath = "tool_photo_path/{$filename}"; if (!Storage::disk('local')->exists($filePath)) { abort(404); } $fileContent = Storage::disk('local')->get($filePath); $mimeType = Storage::disk('local')->mimeType($filePath); return (new Response($fileContent, 200)) ->header('Content-Type', $mimeType); })->name('tool.photos.show');
2. 配置FileUpload组件生成可访问预览URL
修改Filament的FileUpload组件,自定义图片预览地址:
FileUpload::make('tool_photo_path') ->label('Tool photo') ->image() ->directory('tool_photo_path') ->required() ->getImagePreviewUrlUsing(function ($record) { // 提取数据库字段中的文件名(假设字段存储的是相对路径,如"tool_photo_path/xxx.jpg") $fileName = basename($record->tool_photo_path); return route('tool.photos.show', $fileName); });
3. 修正Seeder中的文件路径存储
确保Seeder中存储的是文件相对路径,而非绝对路径:
use Illuminate\Support\Facades\Storage; use App\Models\Tool; // 创建工具记录 Tool::create([ 'name' => '示例工具', 'tool_photo_path' => 'tool_photo_path/sample-tool.jpg', // 存储相对路径 ]); // 将本地文件复制到local驱动指定目录 Storage::disk('local')->putFileAs( 'tool_photo_path', public_path('sample-tool.jpg'), 'sample-tool.jpg' );
关键说明
local驱动的文件默认存放在storage/app目录下,该目录不对外直接公开,因此必须通过路由代理的方式提供访问入口。此前尝试的visibility配置仅针对支持权限设置的存储驱动(如S3),对local驱动无效。
内容的提问来源于stack exchange,提问作者Kishan
相关产品推荐
相关产品推荐

