【问题标题】:Laravel 5.6:Check if a file existsLaravel 5.6:检查文件是否存在
【发布时间】:2019-01-12 13:38:29
【问题描述】:

所以我在 laravel 中创建用户个人资料,如果用户没有上传他/她自己的个人资料图片,我想显示一个通用的个人资料图片,并满足以下 if/else 条件:

@if(false)
    <img src="img/uploads/avatars/{{$user->Uname}}" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@else
    <img src="img/uploads/avatars/{{$user->avatar}}" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@endif

我需要检查是否存在与用户的用户名同名的文件(上传在上述指定位置创建一个具有该名称的文件)。false 是文件存在的条件应该是但我面临着 2 个在其他解决方案中没有发现的问题:

  1. 文件存在于存储之外的路径中。 (它存在于公共 文件夹)

  2. 我想在不使用存储或文件外观的情况下做到这一点。

注意:对 filesystems.php 进行了以下更改

'local' => [
            'driver' => 'local',
            'root' => storage_path('../public/img/uploads/'),
        ]

编辑:问题类似于这里提到的问题,但这个解决方案对我不起作用:Determining If a File Exists in Laravel 5

编辑#2: 最终工作代码:

@if(is_file("img/uploads/avatars/{$user->Uname}"))
<img src="img/uploads/avatars/{{$user->Uname}}" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@else
<img src="img/uploads/avatars/default.jpg" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@endif

【问题讨论】:

  • @if(is_file('/path/to/file.ext')) 呢?
  • 我用 2 个由类名触发的 javascript 函数做了类似的事情。如果你愿意,我可以发布它们。但我不会根据您的特定需求重建它们。首先,图片作为常规 html 请求加载。如果失败,则触发 js。您可以查看您想找到多少个地方并显示图片。在搜索时,它会显示一个很棒的字体加载图标。
  • 我不知道图像在系统中的存储位置。您必须检查保存上传/保存图像代码的方法。就用那个。毕竟它只是一个字符串。
  • @Tpojka,它有效,如果您将评论添加为答案,我会将其标记为正确。
  • 已添加。请检查是否有效。不过我没有测试它。

标签: php laravel filesystems storage


【解决方案1】:

你应该检查文件是否存在

@if(is_file('/path/to/file.ext'))
    // code
@else
    // code
@endif

你可以使用 laravel 助手,比如:

@if(is_file(public_path('img/uploads/avatars/' . $user->Uname)))
    //<img src="{{ asset('img/uploads/avatars' . $user->Uname) }}">

【讨论】:

  • 它确实有效,我现在也为我的问题添加了有效的解决方案,非常感谢。
【解决方案2】:

您的图片 src 中没有文件扩展名。

@if(file_exists('img/uploads/avatars/'.$user->Uname.'png')) 
  <img src="img/uploads/avatars/{{$user->Uname}}.png" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@else
    <img src="img/uploads/avatars/{{$user->avatar}}.png" class="img-thumbnail" alt="{{$user->Uname}}'s Profile Pic">
@endif

根据需要使用“.png”或“.jpg”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 2016-09-08
    • 2019-06-08
    • 2017-01-02
    • 2014-10-02
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多