我正在尝试在视图中显示存储在“public”文件夹之外的图像。这些是简单的配置文件图像,其路径存储在DB中。路径看起来像
/Users/myuser/Documents/Sites/myapp/app/storage/tenants/user2/images/52d645738fb9d-128-Profile (Color) copy.jpg
由于图像存储在每个用户的DB列中,我首先想到的是在User模型中创建一个Accessor来返回图像。我试过了:
public function getProfileImage()
{
if(!empty($this->profile_image))
{
return readfile($this->profile_image);
}
return null;
}
在视图中产生了不可读的字符。我也尝试了file_get_contents()来代替读取文件。有关如何实现这一目标的任何建议吗?
答案 0 :(得分:4)
这个怎么样(我自己测试了它并且有效):
观点:
<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);
}
});
答案 1 :(得分: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';
}
公共/图像/ 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;
?>
如果有人有更好的方法,请指教!我很感兴趣。
答案 2 :(得分:1)
这是@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
路由组中包含了我的意思,这意味着你必须登录才能看到(我的要求),但我可以更好地控制它何时可见,或许改变中间件。
EDIT 忘记提到这是为了Laravel 5.3。