【问题标题】:Cannot load files inside the public folder - Laravel 5.4 [duplicate]无法在公用文件夹中加载文件-Laravel 5.4 [重复]
【发布时间】:2018-11-26 03:26:10
【问题描述】:

我在使用 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')}}" />

在这两种情况下,我都得到了这个看起来(显然)没问题的 URL:http://localhost/public/img/boy.png。我的应用程序在此 URL 上运行良好:http://localhost:8000/

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

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

如何解决这个问题?如何访问公用文件夹中的文件?我花了一整天的时间来解决这个问题!

非常感谢!

【问题讨论】:

  • 设置 url 为 .env 文件(默认为http://localhost),使用asset() 链接公共文件。
  • 我也试过这个解决方案 - 没有结果:(

标签: php html laravel apache laravel-5.4


【解决方案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

【讨论】:

  • 我将如何处理 txt、css 和 js 文件?
【解决方案2】:

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

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

更新

按照this post 中的建议,您可以更改 public_path()

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

根据您的需要调整 __DIR__

【讨论】:

  • 谢谢!我也已经尝试过使用它......但它也不起作用:(
  • 你遇到了什么错误?
  • 你可以直接访问你的文件localhost/public/img/boy.png,因为404错误表明文件不存在。
  • 不,我也不能直接访问我的文件 localhost/public/img/boy.png - 但我的文件在 /public/img/boy.png 下。真的不知道我怎么能得到它以及我的代码有什么问题:(
  • @Joe 重新检查文件名,特别是大写/小写字符。 boy.pngBoy.png 不一样。
【解决方案3】:

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

【讨论】:

  • 图片位于此 URL:http://localhost:8000/img/boy.png - 没有 public 。刚刚检查过:)
猜你喜欢
  • 2017-03-03
  • 2017-09-05
  • 2021-05-10
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 2016-09-02
  • 2021-05-19
  • 2012-01-09
相关资源
最近更新 更多