Skip to content
Advertisement

Laravel how download file for Auth() user in dashboard view

I have big problem to enable Auth users download stored files in laravale storage. Users has in table users field id_message which is unique name of folder where user has file to download.

What has to be made in AuthController which controll dashboard.blade to access user download file ? problem is how add from table variable id_message to file path

File is stored /app/files/{id_message}/*.zip

return response()->download(store_path('app/files/'.(Auth()->user()->id_message).'/*.zip'));

And at the end, what will be in blade

<td><a href="{{ }}">Download</a></td>

Can’t understand why is this problem so hard to solve it for me.

Advertisement

Answer

you can simply use an <a> tag with file url as the href of the tag.

<a href="{{ storage_path('app/files/'.auth()->user()->id_message.'/file.zip') }}" title="Download" target="_blank">
    <button class="btn btn-success">Download</button>
</a>

or you can do it with a controller method.

route

Route::get('download-my-file', 'MyController@downloadZipFile')->name('downloadZipFile');

controller

public function downloadZipFile()
{
   $fileName = storage_path('app/files/'.auth()->user()->id_message.'/file.zip');
   return response()->download($fileName);
   //you can add file name as the second parameter
   return response()->download($fileName, 'MyZip.zip');
   //you can pass an array of HTTP headers as the third argument
   return response()->download($fileName, 'MyZip.zip', ['Content-Type: application/octet-stream', 'Content-Length: '. filesize($fileurl))]);

   //you can check for file existence. 
   if (file_exists($fileName)) {
       return response()->download($fileName, 'MyZip.zip');
   } else {
       return 0;
   }
}

and in view

<a href="{{ route('downloadZipFile') }}" target="_blank">
    <button class="btn btn-success">Download</button>
</a>

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement