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

1.3k views Asked by At

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.

2

There are 2 answers

1
zahid hasan emon On BEST 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">
    Download
</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($fileName))]);

   // 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">
    Download
</a>
0
bhucho On

To create a download link,(See docs)

$filepath = app_path() . '/files/' . Auth::user()->id_message . '/*.zip'
if(\Illuminate\Support\Facades\File::exists($filepath)){
    return response()->download($filepath, 'your_filename', [
        'Content-Length: '. filesize($filepath)
    ]);    
}else{
    return false; //you can show error if it returns false
}

In blade, just call the url (get method),

<td><a href="{{ url('download/' . auth->user()->id_message) }}" 
 target="_blank">Download</a></td>