How to deal with private images in laravel 5?

后端 未结 4 1687
暖寄归人
暖寄归人 2020-12-14 10:32

I am new to Laravel and trying to store private images so that only authenticated users can access them. Firstly I stored images in Public/UserImages folder. But here all th

4条回答
  •  有刺的猬
    2020-12-14 10:56

    Following is how I solved the problem of storing images in Laravel 5 such that only authenticated users can view the images. People who are not authenticated will be directed to a login page. My server is a Ubuntu/Apache2 server.

    1. Create the directory /var/www/YOURWEBSITE/app/Assets/Images

    2. Add route to app/Http/routes.php.

      Route::get('/images/{file}','ImageController@getImage');

    3. Create a controller app/Http/Controllers/ImageController.php

      middleware('auth');
         } 
          public function getImage($filename) {
             $path = '/var/www/YOURWEBSITE/app/Assets/Images/'.$filename;
             $type = "image/jpeg";
             header('Content-Type:'.$type);
             header('Content-Length: ' . filesize($path));
             readfile($path);
      
          }
      
       }
      
    4. In your view you have img tags which have:

      src="{{ url('/images/test.jpg') }}"
      

    This of course assumes test.jpg is a file in /var/www/YOURWEBSITE/app/Assets/Images/

    You can of course add more logic such as not hardcoding the path of the images, etc. This is just a simple example to enforce authentication. Note the use of middleware('auth') in the controller constructor.

提交回复
热议问题