【问题标题】:LARAVEL - Displaying images from the storage folderLARAVEL - 显示存储文件夹中的图像
【发布时间】:2017-09-03 21:43:33
【问题描述】:

我是 Laravel 的新手,想知道是否有人可以通过简单的图片上传来帮助我。

我有一个表单,允许用户在此过程中创建个人资料并为他们的个人资料上传和头像。这一切都完美无缺。这是我的控制器的代码:

if (request()->hasFile('avatar')) {

        $file = request()->file('avatar');

        $file->storeAs('avatars/' . auth()->id(), 'avatar.jpg');
    }

图片保存在 storage/app/avatars/USER-ID/avatar.jpg 中

我不确定如何显示此文件夹中的图像。我一直在寻找解决方案,但我无法使用php artisan storage:link,因为它不是我的服务器。在不使用存储链接的情况下如何解决这个问题?我可以手动创建链接吗?

如果有人可以向我解释一个完美的解决方案!

只要询问您是否需要任何代码 sn-ps。

谢谢!

【问题讨论】:

  • 你收到了吗?
  • @developernator 我还没搞定

标签: php image laravel upload controllers


【解决方案1】:

创建一个符号链接,它将连接storage/app 和public/img 目录,例如:

ln -s /home/laravel/public/img /home/laravel/storage/app

然后只需使用asset() helper 生成链接:

<img src="{{ asset('img/avatars/'.auth()->id().'/avatar.jpg') }}">

【讨论】:

  • 有没有办法自己创建链接?我无权访问命令行
【解决方案2】:

如果您无权访问服务器来创建符号链接,则需要创建一个将图像作为响应返回的路由。

类似的东西:

Route::get('storage/{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;
});

【讨论】:

    【解决方案3】:

    您将需要使用将插件插入控制器的路由来访问受保护的文件,该控制器可以访问文件并将其传递给视图。

    我还建议使用包intervention/image 它可以通过以下方式安装

    composer require intervention/image

    访问图像见下文:

    // 你在web.php的路线

    // Public route to show user avatar
    Route::get('avatars/{id}/{image}', [
        'uses'      => 'TheNameOfYourController@userProfileAvatar'
    ]);
    

    // 在你的控制器文件中。在这个例子中,根据我们上面的名称,它将是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();
        }
    
    }
    

    // 显示图像的刀片视图

    <img src="images/profile/{{ \Auth::user()->id }}/avatar.jpg" alt="{{ \Auth::user()->name }}">
    

    这里有一些参考资料,但这些实例更进一步,并在上传时将文件路径保存到数据库中:

    // 路由示例

    // 控制器示例

    //查看示例

    【讨论】:

    • 非常感谢您的解释,您帮了大忙!参考文献也很棒。再次感谢。
    猜你喜欢
    • 2020-12-19
    • 2019-03-11
    • 2021-02-07
    • 1970-01-01
    • 2018-10-27
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多