LARAVEL-显示存储文件夹中的图像 [英] LARAVEL - Displaying images from the storage folder
问题描述
我是Laravel的新手,我想知道是否有人可以通过简单的图像上传来帮助我.
I'm new to Laravel and was wondering if someone can help me out with a simple image upload.
我有一个表格,允许用户创建个人资料,并在此过程中为其个人资料上传和头像.所有这一切都完美.这是我的控制器中的代码:
I have a form that allows a user to create a profile and upload and avatar for their profile during the process. This all works perfectly. Here is the code from my controller:
if (request()->hasFile('avatar')) {
$file = request()->file('avatar');
$file->storeAs('avatars/' . auth()->id(), 'avatar.jpg');
}
图像保存在storage/app/avatars/USER-ID/avatar.jpg
The image is saved within storage/app/avatars/USER-ID/avatar.jpg
我不确定如何显示该文件夹中的图像.我一直在寻找解决方案,但由于它不是我的服务器,所以无法使用php artisan storage:link
.在不使用存储链接的情况下该如何处理?我可以手动创建链接吗?
I'm not sure how to display the image from this folder. I've looked for solutions but I am unable to use php artisan storage:link
as it is not my server. How do I go about this without using the storage link? Can I create a link manually?
如果有人可以向我解释解决方案,那将是完美的!
If someone could explain a solution to me that would be perfect!
只问您是否需要任何代码片段.
Just ask if you need any code snippets.
谢谢!
推荐答案
您将需要使用插入控制器的路由来访问受保护的文件,该控制器可以访问文件并将其传递给视图.
You will need to access the protected files using a route the plugs into a controller that can access the files and pass it to the view.
我还建议您使用软件包intervention/image
可以通过以下方式安装
I would also recommend using the package intervention/image
it can be installed by
composer require intervention/image
有关访问图像的信息,请参见下文:
See below to on accessing the image:
//您在web.php
// Public route to show user avatar
Route::get('avatars/{id}/{image}', [
'uses' => 'TheNameOfYourController@userProfileAvatar'
]);
//在您的控制器文件中.在此示例中,根据上面的名称,其名称为userProfileAvatar()
// In your controller file. In this example according the name of what we have above it would be userProfileAvatar()
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Image;
class TheNameOfYourController extends Controller
{
/**
* Show user avatar
*
* @param $id
* @param $image
* @return string
*/
public function userProfileAvatar($id, $image)
{
return Image::make(storage_path() . '/avatars/' . $id . '/' . $image)->response();
}
}
//您的刀片视图以显示图像
// Your blade view to display the image
<img src="images/profile/{{ \Auth::user()->id }}/avatar.jpg" alt="{{ \Auth::user()->name }}">
这里有一些参考,但是这些实例可以更进一步,并在上传时将文件路径保存到数据库中:
Here are some references but this intances that go one step further and save the file path the database upon upload:
//路线示例
//控制器示例
//查看示例
https: //github.com/jeremykenedy/laravel-auth/blob/master/resources/views/profiles/edit.blade.php
https: //github.com/jeremykenedy/laravel-auth/blob/master/resources/views/partials/nav.blade.php
这篇关于LARAVEL-显示存储文件夹中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!