Laravel:加载存储在“public”文件夹之外的图像

3

我正在尝试在视图中显示存储在“public”文件夹外部的图像。这些是简单的个人资料图片,其路径存储在数据库中。路径看起来像

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

由于每个用户的图片都存储在数据库的一个列中,我的第一想法是在用户模型中创建一个访问器来返回该图片。我尝试了以下代码:

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

        return readfile($this->profile_image);
    }

    return null;
}

这在视图中会产生无法阅读的字符。我也尝试使用file_get_contents() 替换read file。关于如何实现这一点,有什么建议吗?


这个链接似乎已经很好地解决了如何在<img>标签中使用PHP文件作为src属性的问题。 - user1330388
谢谢,那很有帮助。我已经读过它了,但是直到我重新阅读它之后才理解了。在下面发布了一个答案。 - kablamus
3个回答

6
这个怎么样(我刚刚测试过了,它可以正常工作):
这是视图内容:
<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);
    }
});

这只返回实际的图像源,即/images/theImage.png。 - martyn
这个非常好用。我想要在网站根目录之外展示图片,这正是我一直在寻找的。所以,谢谢! - Maximus

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路由组里,这表示你必须登录才能看到(我的要求),但我需要更多控制它何时可见,也许要修改中间件。

编辑:忘记提到这是用于Laravel 5.3。


1

以下是我的想法:

我试图在视图中显示图片,而不是下载。以下是我想到的方法:

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

视图

{{ 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;
?> 

如果有更好的方法,请启迪我们!我非常感兴趣。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接