我把用户的头像上传到了Laravel存储器里。我如何访问它们并在视图中呈现它们?
服务器将所有请求指向/public,那么如果它们在/storage文件夹中,我如何显示它们?
我把用户的头像上传到了Laravel存储器里。我如何访问它们并在视图中呈现它们?
服务器将所有请求指向/public,那么如果它们在/storage文件夹中,我如何显示它们?
当前回答
如果你像我一样,你以某种方式拥有完整的文件路径(我对所需的照片进行了一些glob()模式匹配,所以我几乎最终得到了完整的文件路径),并且你的存储设置链接良好(即,这样你的路径有字符串storage/app/public/),那么你可以使用我下面的小脏hack:p)
public static function hackoutFileFromStorageFolder($fullfilePath) {
if (strpos($fullfilePath, 'storage/app/public/')) {
$fileParts = explode('storage/app/public/', $fullfilePath);
if( count($fileParts) > 1){
return $fileParts[1];
}
}
return '';
}
其他回答
如果你像我一样,你以某种方式拥有完整的文件路径(我对所需的照片进行了一些glob()模式匹配,所以我几乎最终得到了完整的文件路径),并且你的存储设置链接良好(即,这样你的路径有字符串storage/app/public/),那么你可以使用我下面的小脏hack:p)
public static function hackoutFileFromStorageFolder($fullfilePath) {
if (strpos($fullfilePath, 'storage/app/public/')) {
$fileParts = explode('storage/app/public/', $fullfilePath);
if( count($fileParts) > 1){
return $fileParts[1];
}
}
return '';
}
首先,您需要使用artisan命令为存储目录创建一个符号链接
php artisan storage:link
然后在任何视图中,你都可以像这样通过url helper访问你的图像。
url('storage/avatars/image.png');
如果你想要加载少量的私有图像,你可以将图像编码为base64,并直接将它们回显到<img src="{{$image_data}}">:
$path = image.png
$full_path = Storage::path($path);
$base64 = base64_encode(Storage::get($path));
$image_data = 'data:'.mime_content_type($full_path) . ';base64,' . $base64;
我提到private是因为你应该只使用这些方法,如果你不想存储图像通过url公开访问,相反,你必须总是使用标准的方式 (链接存储/公用文件夹,并使用HTTP服务器提供图像)。
注意编码到base64()有两个重要的缺点:
这将增加图像大小约30%。 你在一个请求中组合了所有的图像大小,而不是并行加载它们,这对于一些小的缩略图应该不是问题,但对于许多图像避免使用这种方法。
你可以在控制台中运行这个命令来创建链接:
php artisan storage:link
对我来说,它与子文件夹路由一起工作
Route::get('/storage/{folder}/{filename}', function ($folder,$filename)
{
$path = storage_path('app/public/' .$folder.'/'. $filename);
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;
});