How to deal with private images in laravel 5?

后端 未结 4 1783
暖寄归人
暖寄归人 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 11:03

    I got the same issue some days ago and came up with this solution:

    1. First thing you have to do is upload the file to a non-public directory. My app is storing scanned invoices, so I'm going to place them inside storage/app/invoices. The code for uploading the file and generating the url would be:

      // This goes inside your controller method handling the POST request.
      
      $path = $request->file('invoice')->store('invoices');
      $url = env('APP_URL') . Illuminate\Support\Facades\Storage::url($path);
      

      The url returned should result in something like http://yourdomain.com/storage/invoices/uniquefilename.jpg

    2. Now you have to create a controller that uses the auth middleware to ensure the user is authenticated. Then, define a method that grabs the file from the private directory and returns it as a file response. That would be:

      middleware('auth');
          }
      
          public function __invoke($file_path)
          {
              if (!Storage::disk('local')->exists($file_path)) {
                  abort(404);
              }
      
              $local_path = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $file_path;
      
              return response()->file($local_path);
          }
      }
      
    3. The last thing is register the route inside your routes/web.php file:

      Route::get('/storage/{file_name}', 'FileController')->where(['file_name' => '.*'])
      

    So there you have it, a pretty reusable snippet for all your projects that deals with private files :)

提交回复
热议问题