无法加载公用文件夹中的文件 - Laravel 5.4

时间:2018-06-16 16:54:08

标签: php html laravel apache laravel-5.4

我在使用Laravel 5.4时遇到了问题。我需要加载一些公共文件夹public/img下的图片。为此,我在刀片视图中尝试了以下几行代码:

  1. <img src="{{Config::get('app.url')}}/public/img/boy.png" width="30"/>
  2. <img src="{{url('/img/boy.png')}}" />
  3. 在这两种情况下,我都会看到这个看起来很明显的网址:http://localhost/public/img/boy.png。我的应用程序在此网址上正常运行:http://localhost:8000/

    问题是pic(以及同一文件夹中的其他文件)无法加载。在HTML页面上,我在控制台中收到以下错误:http://localhost/public/img/boy.png 404 (Not Found)

    怎么可能?实际上,如果我尝试转到http://localhost/public/img/boy.png,我会收到页面不存在的错误。

    如何解决这个问题?如何访问公用文件夹中的文件?我一整天都在努力解决这个问题!

    非常感谢你!

3 个答案:

答案 0 :(得分:1)

在您的路线中添加以下内容并尝试。我使用存储文件夹而不是公共路径。

Route::get('/images/{filename}', function ($filename, Illuminate\Http\Request $request)
{
    $path = public_path() . "/img/$filename";
    // $path = storage_path() . "/images/$filename"; //i normally use this, as i put it in storage folder

    //add validations if you want

    if(!File::exists($path)) abort(404);

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

所以现在当你转到http://localhost/images/boy.png时,你会得到/public/img/boy.png

答案 1 :(得分:0)

您可以使用资产它会生成url到png文件。

{{ asset('img/boy.png') }}

<强>更新

根据this post的建议,您可以更改 public_path()

$app->bind('path.public', function() { return __DIR__; });

根据您的需要调整 __ DIR __

答案 2 :(得分:0)

您的应用正在投放或http://localhost:8000/,因此您的图片应为此网址http://localhost:8000/public/img/boy.png。 我认为这是有道理的。您正在端口8000上运行您的应用程序,因此您应该为所有组件指定端口