Download file from storage in Laravel

Last Updated: July 12, 2021

In this article, we are going to discuss how you can view or download files from the storage.

Before downloading the file, you can upload the file with Laravel.

Routes

You can add the following code to your routes\web.php file

Route::get('view', 'UploadController@view');
Route::get('get/{filename}', 'UploadController@getFile')->name('getfile');

Action in Controller

You have the getFile action in your UploadController. So you can add the following code to it.

function getFile($filename){
    	$file=Storage::disk('public')->get($filename);
		return (new Response($file, 200))
              ->header('Content-Type', 'image/jpeg');
    }

You get the file from the storage by giving the file name and get the response with the correct content type.

You have the view action also. You can add the following code to it

$files = Storage::files("public"); 
$images=array(); 
foreach ($files as $key => $value) { 
  $value= str_replace("public/","",$value); 
  array_push($images,$value); 
} 
return view('display', ['images' => $images]);

You get the image files from the public folder and extract the name of these files and pass them to your view

View

Finally, you can create a view display.blade.php in resources\view folder.

 @foreach($images as $image)
  <div> 
     <img src="{{route('getfile', $image)}}"  class="img-responsive" />
  </div>                
 @endforeach