【问题标题】:Laravel: load images stored outside 'public' folderLaravel:加载存储在“公共”文件夹之外的图像
【发布时间】:2014-02-03 16:52:19
【问题描述】:

我正在尝试在我的视图中显示存储在“公共”文件夹之外的图像。这些是简单的配置文件图像,其路径存储在数据库中。路径看起来像

/Users/myuser/Documents/Sites/myapp/app/storage/tenants/user2/images/52d645738fb9d-128-Profile (Color) copy.jpg

由于图像为每个用户存储了一个 DB 列,我的第一个想法是在 User 模型中创建一个访问器来返回图像。我试过了:

public function getProfileImage()
{   
    if(!empty($this->profile_image))
    {   

        return readfile($this->profile_image);
    }

    return null;
}

这会在视图中产生不可读的字符。我还尝试使用 file_get_contents() 代替读取文件。关于如何实现这一点有什么建议吗?

【问题讨论】:

标签: php image laravel


【解决方案1】:

这个怎么样(我自己测试了一下,效果很好):

观点:

<img src="/images/theImage.png">

Routes.php:

Route::get('images/{image}', function($image = null)
{
    $path = storage_path().'/imageFolder/' . $image;
    if (file_exists($path)) { 
        return Response::download($path);
    }
});

【讨论】:

  • 这只是返回实际的图像src,即/images/theImage.png
  • 这非常有效。我想在 webroot 之外显示图像,这正是我想要的。所以,谢谢!
【解决方案2】:

这是@Mattias 答案的略微修改版本。假设该文件位于 Web 根目录之外的 storage/app/avatars 文件夹中。

<img src="/avatars/3">

Route::get('/avatars/{userId}', function($image = null)
{
  $path = storage_path().'/app/avatars/' . $image.'.jpg';
  if (file_exists($path)) {
    return response()->file($path);
  }
});

可能需要和else。我还把我的包裹在middleware auth Route Group 中,这意味着你必须登录才能看到(我的要求),但我可以更好地控制它何时可见,也许可以改变中间件。

编辑 忘了说这是针对 Laravel 5.3 的。

【讨论】:

    【解决方案3】:

    这是我想出的:

    我试图在视图中显示图像,而不是下载。这是我想出的:

    • 请注意,这些图像存储在公用文件夹上方,这就是为什么我们必须采取额外步骤才能在视图中显示图像的原因。

    景色

    {{ HTML::image($user->getProfileImage(), '', array('height' => '50px')) }}
    

    型号

    /**
     * Get profile image
     *
     * 
     *
     * @return string
     */
    public function getProfileImage()
    {   
        if(!empty($this->profile_image) && File::exists($this->profile_image))
        {       
    
            $subdomain = subdomain();
    
            // Get the filename from the full path
            $filename = basename($this->profile_image);
    
            return 'images/image.php?id='.$subdomain.'&imageid='.$filename;
        }
    
        return 'images/missing.png';
    }
    

    public/images/image.php

    <?php
    
    $tenantId = $_GET["id"];
    $imageId = $_GET["imageid"];
    
    $path = __DIR__.'/../../app/storage/tenants/' . $tenantId . '/images/profile/' . $imageId; 
    
     // Prepare content headers
    $finfo = finfo_open(FILEINFO_MIME_TYPE); 
    $mime = finfo_file($finfo, $path);
    $length = filesize($path);
    
    header ("content-type: $mime"); 
    header ("content-length: $length"); 
    
    // @TODO: Cache images generated from this php file
    
    readfile($path); 
    exit;
    ?> 
    

    如果有人有更好的方法,请不吝赐教!!我很感兴趣。

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 2020-05-22
      • 1970-01-01
      • 2021-09-08
      • 2021-04-21
      • 1970-01-01
      • 2017-02-03
      • 2017-07-22
      • 2020-03-02
      相关资源
      最近更新 更多