laravel 检索存储在存储文件夹中的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41138642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieving image stored in storage folder
提问by Sara M.
Using laravel 5.3, I am trying to retrieve an image in a view. How I could do this? folder structure: storage/app/avatard
使用 laravel 5.3,我试图在视图中检索图像。我怎么能做到这一点?文件夹结构:storage/app/avatard
Here is the code:
这是代码:
public function storeAvatar(Request $request, $username)
{
$user = User::where('name', $username)->first();
$avatar = $request->file('avatar')->store('avatars');
$avatar = explode('avatars/', $avatar);
$user->user_setting()->updateOrCreate(
['user_id' => $user->id],
['avatar' => $avatar[1]]
);
return back();
}
This is how the image path is saved in the database:
这是图像路径在数据库中的保存方式:
/users/avatar/default.png
/users/avatar/default.png
回答by aimme
Somewhat like this you can achieve as storage path is directly unavailable for public. you need to provide public url in route like this.
有点像这样您可以实现,因为存储路径对公共直接不可用。您需要在这样的路线中提供公共网址。
In view
在视图中
<img src="{{route('avatar',$filename)}}" />
or
或者
<img src="/avatars/{{$filename}}" />
In routes/web.php
在路由/web.php
Route::get('/avatars/{filename}', function ($filename)
{
$path = storage_path() . '/avatars/' . $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;
})->name('avatar');
回答by Jagadesha NH
First create a storage link by typing in
首先通过键入创建存储链接
php artisan storage:link
and then
进而
<img src={{ asset('storage/folder_name/image_name') }} />
回答by Jonathon
If you store your files in the storage/app/public
directory as per the Laravel documentationyou can create a symbolic link on Unix/Linux systems that will allow you to reference the files as if they were in the public
directory.
如果您storage/app/public
按照Laravel 文档将文件存储在目录中,您可以在 Unix/Linux 系统上创建一个符号链接,这将允许您引用文件,就像它们在public
目录中一样。
Create the symbolic link using the artisan command:
使用 artisan 命令创建符号链接:
php artisan storage:link
In your views you are then able to reference the files using
在您的视图中,您可以使用以下方法引用文件
{{ asset('storage/path/to/file.png') }}
回答by Alblez
Consider if you are using Homestead, you must create the symbolic link from the virtual machine;
考虑一下,如果您使用的是 Homestead,您必须从虚拟机创建符号链接;
In your terminal:
在您的终端中:
homestead ssh
go to your project folder:
转到您的项目文件夹:
cd Code/YOUR_PROJECT
now you can execute the command:
现在你可以执行命令:
php artisan storage:link