You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel网站检测到app/public文件夹图片却无法正常显示的求助

问题:浏览器仅显示破碎图片图标,无法加载app/public下匹配参考值的图片

需求:在浏览器中显示位于app/public文件夹内的图片,流程为:

  • 获取参考值;
  • 在app/public及其子文件夹中查找所有包含该参考值的文件;
  • 在blade文件中展示这些图片。

当前代码:

Blade文件代码

<div class="py-16">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            
                @foreach($matchingFiles as $file)
                    <!--<img src="{{asset('storage/'.$file->getPathname()) }}" alt="{{$file->getFilename() }}">-->
                    <img src="{{ asset('dossiers/' . urlencode($file->getPathname())) }}" alt="{{ $file->getFilename() }}">
                @endforeach
</div>
</div>

Controller代码

public function consult($id){
        $tableData=alignement::find($id);
        $reference=$tableData->reference;
        $directory=storage_path("app/public/dossiers");
        $contents=File::allFiles($directory);
        $matchingFiles=[];

        foreach($contents as $file){
            if(strpos($file->getFilename(),$reference) !==false){
                $matchingFiles[]=$file;
            }
        }
        return view('displayFolder',['matchingFiles'=>$matchingFiles]);
    }

现状:系统能检测到匹配的图片,但浏览器仅显示破碎的图片图标。曾将文件从app/dossiers移至app/public/dossiers,问题依旧。


解决方案

1. 创建storage软链接

Laravel中storage/app/public目录的文件需要通过public目录下的storage软链接对外访问,执行以下Artisan命令创建链接:

php artisan storage:link

2. 修正Controller的路径传递逻辑

$file->getPathname()返回的是服务器绝对路径,前端无法直接使用,需要提取文件相对于storage/app/public的相对路径:

public function consult($id){
    $tableData = alignement::find($id);
    $reference = $tableData->reference;
    $directory = storage_path("app/public/dossiers");
    $contents = File::allFiles($directory);
    $matchingFiles = [];

    foreach($contents as $file){
        if(strpos($file->getFilename(), $reference) !== false){
            // 提取相对路径
            $relativePath = str_replace(storage_path('app/public'), '', $file->getPathname());
            $matchingFiles[] = [
                'path' => ltrim($relativePath, '/'),
                'name' => $file->getFilename()
            ];
        }
    }
    return view('displayFolder', ['matchingFiles' => $matchingFiles]);
}

3. 修正Blade的图片路径

通过asset('storage/xxx')拼接正确的访问路径:

<div class="py-16">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        @foreach($matchingFiles as $file)
            <img src="{{ asset('storage/' . $file['path']) }}" alt="{{ $file['name'] }}">
        @endforeach
    </div>
</div>

4. 验证文件权限

确保Web服务器能读取目标目录及文件:

chmod -R 755 storage/app/public/dossiers
chown -R www-data:www-data storage/app/public/dossiers # 根据服务器实际用户调整

内容的提问来源于stack exchange,提问作者DevilBoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:22:56